question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
5,052,563
5,062,633
C++/OpenSSL: Use root CA from buffer rather than file (SSL_CTX_load_verify_locations)
I am using OpenSSL to verify a server's certificate. Since OpenSSL is shipped without any built-in root CAs, we must distribute the root CA certificate ourselves with our software (we statically-link OpenSSL). Ordinarily, the way to do this is to distribute a certificate file in PEM format and call SSL_CTX_load_verif...
The function SSL_CTX_get_cert_store() can be used to get a handle to the certificate store used for verification (X509_STORE *), and the X509_STORE_add_cert() function (in openssl/x509_vfy.h) can then be used to add a certificate directly to that certificate store.
5,052,652
5,052,678
FuncPtrTab to Method
I'm having a hard time trying to make this work. I'm trying to execute a method stocked in a method pointer tab. here is my example : void class1::fct1(); void Class1::fct2(); void Class1::manageFct() { static const void (*ptrFuncTab)[] = { &Class1::fct1, &Class1::fct2 }; opCode = 0; pt...
Do this: typedef void (Class1::*MemFn)(); static const MemFn ptrFuncTab[] = { &Class1::fct1, &Class1::fct2 }; What you were using is called pointer-to-function; what I'm using is called pointer-to-member-function. And they're not the same thing. Use this function table as: Class1 c; (c.*ptrFuncTab[0])(); Or...
5,053,244
21,186,208
Is it possible to embed a HTTP server in a Google Chrome extension?
Do you think it would be possible to embed a HTTP server inside a Google Chrome extension? I've seen other Google Chrome extensions execute native code and apparrently they do it by using NPAPI, but I have no idea what that is. And it's really freaking me out, as I'm no C++ expert or anything like that. So I feel a lit...
Here is info on making a web-server in a Chrome app: https://developers.google.com/live/shows/7320022-5001
5,053,259
5,053,269
Self-reproducing program
I am questioning my solution to the last exercise in Accelerated C++: Write a self-reproducing program. Such a program is one that does no input, and that, when run, writes a copy of its own source text on the standard output stream. My solution: using std::string; using std::cout; using std::endl; using std::ifstrea...
A program that prints itself is called Quine. I think your solution wouldn't be considered valid: quines usually aren't allowed to read files (nor to get any other kind of input). It's possible to writ a Quine C++ program, here you could find many quine implementations in several languages.
5,053,337
5,053,397
How to cast a void pointer to a pointer when dereferencing?
int x = 5; int *xPtr = &x; void **xPtrPtr = &xPtr; printf("%d\n", *(int*)*xPtrPtr); I have a void pointer pointing to an int pointer. What is the syntax for properly casting the void pointer when I want to dereference? The above code quits with: error: invalid conversion from ‘int**’ to ‘void**’ Thank you!
For void pointers, you don't really need to know how many indirections there are. #include <iostream> int main(void){ int x = 5; int* pX = &x; void* pV = &pX; std::cout << "x = " << **(int**)pV << std::endl; // better use C++-Style casts from the beginning // or you'll be stuck with the lazyne...
5,053,382
5,057,248
Override new operator in C++ while crtdbg.h is causing conflicts
While trying out some memory tracking and preparation for my own memory manager, I tried to override the new operator. The article on flipcode was my main guideline in this process ( http://www.flipcode.com/archives/How_To_Find_Memory_Leaks.shtml ). After implementing the techniques described in that article, I am left...
Allright, the way I solved it for now, without having to use a custom 'new' define is that I've made a generic header file, let's say 'Engine.h' that is included in every file. This can be enforced by using the Forced Include File in the Project Settings / Configuration Properties / C/C++ / Advanced. This file contains...
5,053,408
5,113,413
Weird cout behavior in C++
I am getting some weird behavior when using cout in my programm, which is similar to the following: ... char *input = realpath(argv[1], NULL); char *output = argv[2]; char *tarout = new char[strlen(output)+6]; strcpy(tarout, output); strcat(tarout, ".temp"); cout << "Tarout: " << tarout << endl; int tRet = tarball(i...
new/malloc do not initialize memory, so I'm fairly certain that you have no NULL terminator at the end of tarout. I suspect if you run your original code through a debugger or simply print out *(tarout+5), you would see that there is no '0' there. Given your comments regrading the use of std::string, I would write: con...
5,053,411
5,053,512
Random String Generation
#include <iostream> #include <string> #include <cstdlib> using namespace std; char *charStr; int stringLength; void genRandom() { static const char alphanum[] = "0123456789" "!@#$%^&*" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; for (int i = 0; i < stringLength...
Several issues with your code: cout < charStr; should be: cout << charStr; If you compile with the g++ -Wall argument (warning all), that error becomes easily apparent. Also, you never set the value of stringLength! This is one example of why you generally should not use global variables--it can be hard to keep tra...
5,053,419
5,053,666
Cross platform autorun
I am writing a program in qt that will be installed on a flash drive. I need it to run on several operating systems as soon as it is plugged in. I was thinking I could do this by putting all of the different os compiles in separate folders and having the autorun for each os in the first part of the drive. Would this wo...
It would certainly work - basically each autorun configuration file is OS specific, and you can specify exactly which executable to run on plug-in. The Sandisk U3 platform is a rather devious trick around a typical Windows setting, which forbids autorun from a flash device, but allows it nonetheless on an CDrom drive. ...
5,053,552
5,053,733
Consequences of using Structured Exception Handling (SEH)?
I see Doug Harrison has made a good statement of what is "wrong" with using (i.e. catching) structured exceptions (see question #3). But what other consequences are there? For example, what happens if I have several projects compiled with /eha, mixed with other projects compiled with /ehs? Are there issues when the ...
/EHa disables an optimization. With /EHs in effect, the compiler can omit exception filters if it can be sure that no C++ exception is ever thrown by the code wrapped in a try {}. That's a small space optimization on x86 and x64, very small time optimization on x86. Problem is, those filters are needed if you catch ...
5,053,767
5,053,844
C++ , Latency in loading data Structure from memory to cache
I have following function in C++ int readData ( Class1 *data) { //StartTime try{ char *a1 = data->name1; int a2 = data->age1; char *b1 = data->name1; int b2 = data->age1; . . . char *e1 = data->name5; int e2 = data->age5; ...
What happened in between your calls? The most obvious thing is that the CPU L1, L2 cache is filled with other data since you did nothing for several seconds. When you access the memory locations again the data has to be loaded from the main memory again which is much slower. C++ has no GC or such thing so there is not...
5,053,769
5,053,807
Build a queue of queues without using the STL
I'm attempting to build a queue of queues that I can use to manage multiple data sets, but I'm not sure how. Simply delaring queue<queue> doesn't work and returns the following error: error: type/value mismatch at argument 1 in template parameter list for ‘template<class Type> class queue’ main.cpp:18: error: expecte...
A queue must have a type. You are creating a queue of queues of.... nothing. So it's reading the token queue inside of the < and > as an error, not a type. queue is not a type, technically. queue<int> is a type. Do you want to write your own queue class or your own queue of queues class? What I'd advise is writing your...
5,053,785
5,054,641
How to build boost for msvc9.0 instead of msvc10.0?
I've run the bootstrap batch and then the bjam exe, but as I have MSVC 2010 it generates the -vc100- files in the $boost\stage\lib. I'm using vc90 libraries so I need the *-vc90-* files, but if I pass the --toolset=msvc-9.0 option to bjam, it gives me the following errors: ...failed compile-c-c++ bin.v2\libs\wave\build...
solved. Just needed to add VC9 compiler path to the %PATH% system var.
5,053,846
5,053,900
Problem with simple overloading of functions
The set functions' idea: First argument is a reference, allocates space to hold copy of testing, sets str member of beany to point to the new block, copies testing to new block, and sets ct member of beany. Problem: 1) Line that contains: for (int i = 0; i < temp.length(); i++) Error:expression must have a class ty...
temp is a const char*. That type does not provide any kind of length facilities- it is not an object and does not have a length() member method. Use a std::string- that is what it is for.
5,053,977
5,054,185
How can I catch an invalid fgetpos call as a C++ exception on Windows?
In Visual C++ 2008, I want to "catch" an exception generated as shown here: try { int foo = 20; ::fgetpos(0, (fpos_t*)&foo); } //... Here are adjustments I've made to attempt a successful catch: SEH is activated (/eha) I've added a catch(...) I've added a _set_se_translator vector. I've added/adjusted to SEH ...
Since the code in your dump corresponds to STATUS_INVALID_CRUNTIME_PARAMETER, try _set_invalid_parameter_handler
5,054,087
5,054,121
Declare a function accepting generic iterator
Given this code, is it possible to change dumpStrings() to be able to iterate over any container of string, like say a list<string> ? #include <vector> #include <string> #include <ostream> #include <iostream> using namespace std; void dumpStrings(vector<string>::iterator it, vector<string>::iterator end) { while...
yes http://www.boost.org/doc/libs/1_45_0/libs/utility/enable_if.html http://www.cplusplus.com/reference/std/iterator/iterator_traits/ http://www.boost.org/doc/libs/1_44_0/libs/type_traits/doc/html/boost_typetraits/reference/is_same.html template<class I> typename enable_if< is_same<typename iterator_traits<I>::valu...
5,054,149
5,054,158
Relational operator overloading in a templated class (C++)
I am creating a KeyValuePair class, and am running into some trouble when overloading the relational operators. It is my understanding that this is necessary for using the std sort functions (I am trying to have sort based on the values) Here is the header: template <typename K, typename V> class KeyValuePair { public...
kvp1 and kvp2 are pointers to KeyValuePair<char, int> objects. They are not themselves KeyValuePair<char, int> objects. *kvp1 < *kvp2 would invoke your overloaded operator<. You cannot overload operator< for two pointer types because the built-in operator< for pointers will be used. std::pair can be used as a key-val...
5,054,290
5,054,326
Using a Constant Character Pointer in a std::set Container: Memory Consumption
I'm currently working on a device with very little memory (4MB) and I have a component of my program that requires an std::set. I would like to migrate this set from using std::string to using const char pointers but I was wondering how memory is allocated to constant character pointers when used in a std::set. Will th...
The STL containers always calk the default destructors for elements they contain when they are cleaned up. For a set holding raw ‘char *‘ pointers, this will do nothing and the memory will be leaked. You are responsible for cleaning ip this sort of memory yourself. For this reason, it's generally considered bad pract...
5,054,438
5,054,492
Accelerated C++: Can I substitute raw pointers for smart pointers?
I love this book, sadly it does not cover smart pointers as they were not part of the standard back then. So when reading the book can I fairly substitute every mentioned pointer by a smart pointer, respectively reference?
Well, there are different kinds of smart pointers. For example: You could create a scoped_ptr class, which would be useful when you're allocating for a task within a block of code, and you want the resource to be freed automatically when it runs of of scope. Something like: template <typename T> class scoped_ptr { pub...
5,054,484
5,070,790
Function argument type followed by *&
I have some code written by someone else in which some functions take arguments whose data types are followed by a *&. I'm used to functions taking one or the other, e.g. taking a "double *" or a "double &" but not both. It would have thought they would just cancel out. Here's an example, and this is all from their co...
Well, I tried casting to a (const unsigned int *), and that did not work (wouldn't build). In the end, I had to fully cast to a (const unsigned int *&) in the foo function example in my original post. Hope this helps. Thanks. As an aside, the reason I did not go the route of making pbuff const from the beginning in my...
5,054,564
5,054,613
Different values on each hashing approach
can someone please tell me what i'm doing wrong? i'm trying to hash a value with murmurhash, but i get different values every time: std::string str = "some test string"; char out[32]; MurmurHash3_x86_32(str.c_str(), str.length(), 0, out); unsigned int hash = reinterpret_cast<unsigned int>(out);
It looks to me like MurmurHash3_x86_32 is returning a 32 bits hash value. But you're giving it a 32 bytes output parameter. You could simply: std::string str = "some test string"; unsigned int hash; MurmurHash3_x86_32(str.c_str(), str.length(), 0, &hash);
5,054,679
5,054,695
What does "a member template of a class" refer to in the C++ standard?
The C++ standard states: A template defines a family of classes or functions. template-declaration: exportopt template < template-parameter-list > declaration The declaration in a template-declaration shall declare or define a function or a class, or define a member function, a member class or a static data membe...
A member template of a class is a member function that is itself a template, like these: class test { template <typename T> void foo(); // member template of class }; template <typename T> void test::foo<T>() {} // definition template <typename T> class test2 { template <typename U> void foo(); // ...
5,054,722
5,055,204
Creating terrain - .RAW files vs .x files
Which one of the two files should I be using. What is the difference?
Use whatever works for you. The differences: mainly that .RAW files need to be loaded and managed by you. .X files have a large set of libraries available and support for them exists in DX already.
5,054,924
5,054,937
Storing Chars Into Strings in C++
So right now I have this code that generates random letters in set increments determined by user input. #include <iostream> #include <string> #include <cstdlib> using namespace std; int sLength = 0; static const char alphanum[] = "0123456789" "!@#$%^&*" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; int ...
Just add string s(sLength, ' '); before while (true), change cout << genRandom(); to s[x] = genRandom(); in your loop, and remove the cout << endl; statement. That will replace all of the printing by putting the characters into s.
5,055,147
5,055,155
C++ library linking to C++ dll using g++
I've seen numerous questions and answers to people with C libraries linking to C++, or C++ libraries linking to C... I however have a C++ library linking to C++, and am getting the same symptoms as people mixing C and C++ together (undefined reference during linking). This is my g++ line: g++ -L C:/MyLibraries mycode.c...
Visual Studio and g++ use very different conventions for things like name mangling, vtable layout, and such so that it is not safe to link libraries built with them together (other than when they only communicate through C interfaces). There is more information at http://www.mingw.org/wiki/MixingCompilers on the MinGW...
5,055,288
5,055,320
Visual Studio C++ 2010 express and OpenGL
I want to be able to compile OpenGL4.1 (C/C++) applications from VisualC++ 2010. After doing a search I only found: http://www.opengl.org/sdk/ and the documentation: (which is fine) http://www.opengl.org/sdk/docs/man4/ Which is a bit confusing, and I really don't know what to install to get started. I can't even find a...
You don't need to download anything to use OpenGL. Just add #include <gl/GL.h> #include <gl/GLU.h> to the top of your source file. And you also need to link the libraries, which in MSVC can be done like this: #pragma comment(lib, "opengl32.lib") #pragma comment(lib, "glu32.lib") With the header files provided with mi...
5,055,334
5,055,367
trouble with memory allocation for a class member vector, given an array of objects of that class?
My basic program structure is this: class B1 { vector <someStruct> aStruct; //some struct contains a vector of 'someotherStruct's, etc B1() { cout << &aStruct << " ";}; }; class B2 {B1* pB1;}; class A { B1 object_B1; B2 object_B2; A() { objectB2.pB1 = &object_B1;}; }; int main() { vector ...
You are missing a copy ctor for A and the default copy semantics copy the pointer value from one B2 object to another. Each item in the struct sees the same address because they are all copied from the same source object. When this pointed-to object is later destroyed, you'll have UB accessing it. A a1; A a2 = a1; as...
5,055,427
5,055,450
Returning non-const reference from a const member function
Why does returning the reference to a pointed-to member variable work, but not the other? I know that a const member function should only return const references, but why does that not seem true for pointers? class MyClass { private: int * a; int b; public: MyClass() { a = new int; } ~MyClass() { d...
int & geta(void) const { return *a; } // good? int & getb(void) const { return b; } // obviously bad In a const-function, every data member becomes const in such way that it cannot be modified. int becomes const int, int * becomes int * const, and so on. Since the type of a in your first function becomes int * cons...
5,055,443
5,056,462
Boost-python How to pass a c++ class instance to a python class
I am new to boost python. I have to first init a cpp class instance in cpp code, and then pass this cpp instance to python code, use a python class instance to invoke it(the cpp instance). I have tried the Python/C API way, but failed, so I wonder how to pass a c++ class instance to a python class. The following is my...
Pass the object pointer via boost::python::ptr to python. This will prevent the python interpreter from makeing a copy: #include <boost/python.hpp> #include <string> #include <iostream> using namespace boost::python; using namespace std; class World { private: string name; public: void set(string name) { ...
5,055,604
5,055,892
built-in type variable is returned from a function
If a local object is returned in a function call, it has to do at least three steps: Copy constructor is called to hold a copy. Destroy local object. A copy is return. For example: x = y + z If x is an integer object. A copy of y + z should be returned, then a new object is created, then assignment operator ...
The language specification does not say "how it is done" for built-in types and built-in operators. The language simply says that the result of binary + for built-in types is an rvalue - the sum of the operand values. That's it. There's no step-by-step description of what happens when a built-in operator is used (with ...
5,055,636
5,055,648
Casting an Object to char* for saving/loading
I have a small question. I'm writing a loading/saving function for getting plain geometry data from a saved file. The objects involved are instanced from classes with a lot of data in them, but they all use just plain old data, and no pointers/allocated memory and the like. Is it possible to load the file into an allo...
Is it possible to load the file into an allocated char* array, typecast that to, say, Geometry* It's possible. I've done a similar job. I had used two chained static_cast to do this, as: char *buffer; //.. Geometry *g = static_cast<Geometry *>(static_cast<void*>(buffer)); //reverse buffer = static_cast<char*>(st...
5,055,949
5,055,985
gcc 4.5.1 vs VC2010 template partial specialization: which is C++0x conformant?
The following compiles with VC2010 but fails with gcc 4.5.1 with -std=c++0x: template <class T, class TBase> class TestBase : public TBase { public: // Helper functor template <unsigned int t_u, class TRet = int> struct Helper { TRet operator() (int x = 0, int y = 0) { return...
In the first code snippet, Helper is not a dependent name. Because it's not dependent, it must be resolved when the template is parsed rather than when it is instantiated. This is required both in C++03 and C++0x. Using the typedef makes it a dependent name so it is resolved on instantiation. You could also use type...
5,056,059
5,177,978
QTreeWidget for Projects
Well. I'm working on an IDE. Some of you maybe saw a post about it. Well, i have no clue of how QTreeWidget & QtreeWidgetItem works since can't find a demo and the documentation doesn't help. Well, what i'm trying to do is a IDE that you open the project file and then include all the files of the project to the tree. (...
A simple solution would be to directly use QTreeWidgetItem. For every file in your project, create an instance of QTreeWidgetItem: QTreeWidgetItem *file = new QTreeWidgetItem(browserWidget); file->setText(0, filename); Where "filename" is a string containing the name of your file. You can get the filename by parsing ...
5,056,117
5,056,128
Do I need to #undef a local #define? Is there such a thing as a local define?
Sometimes to make things easier to write and read, I write some local #define macros within functions (for example, #define O_REAL Ogre::Real). Do I need to #undef the local #define to ensure that it stays within a certain block of code? Or does it automatically #undef when it goes out of scope? Does it even have a co...
#define does not respect any C++ scope. There is no such thing as a "local" #define. It'll be in effect until it is #undef-ed. The preprocessor's macro mechanism is just like the "find-and-replace" functionality found in most text editors; it has no respect for the contents of the file. In other words, if you want your...
5,056,372
5,056,393
Using pointer for crossing over all elements in INTEGER array
Is there a way to cross over all elements in integer array using pointer ( similiar to using pointer to cross over string elements).I know that integer array is not NULL terminated so when I try to cross over array using pointer it overflows.So I added NULL as a last element of an array and it worked just fine. int arr...
The reason that you can iterate across a C-style string using pointers is that of the 256 different character values, one has been specifically reserved to be interpreted as "this is the end of the string." Because of this, C-style strings can't store null characters anywhere in them. When you're trying to use a simil...
5,056,390
5,056,404
when copying objects, problem w/ staticaly declared array, that is a member of a member object of the object being copied
I have a vector of A objects. class A contains a member object of type B. class B contains a statically declared array of bool. When I copy an A object into the vector, the values in the bool array are lost. I though this shouldn't be a problem because the array of bool is statically declared. Do I need to handle this ...
You shouldn't need to define a copy constructor to do this. I'm not sure what you mean by "static arrays," since there are two meanings, but neither require a copy constructor. If you mean "array that's statically sized," like this: class MyClass { private: bool myArray[137]; }; Then the default copy constructor ...
5,056,429
5,056,453
Getting the least significant byte
I haven't tested on a big endian processor but would this always give me least significant byte? int i = 12345678; unsigned char c = static_cast<unsigned char>(i);
Yes, this will always give you the least-significant byte. The C++ spec (§4.7/2) guarantees that narrowing conversions always discard the most-significant bytes by giving back the smallest value congruent to the original integer, modulo 2n, where n is the number of bits in the target type. That said, there's no guaran...
5,056,520
5,056,634
Algorithm for selecting all edges and vertices connected to one vertex
I'm using Boost Graph to try and make sense of some dependency graphs I have generated in Graphviz Dot format. Unfortunately I don't know very much about graph theory, so I have a hard time framing what I want to know in terms of graph theory lingo. From a directed dependency graph with ~150 vertices, I'd like to "zoom...
Ok, so I'll translate and adapt my tutorial to your specific question. The documentation always assumes tons of "using namespace"; I won't use any so you know what is what. Let's begin : #include <boost/graph/adjacency_list.hpp> #include <boost/graph/astar_search.hpp> First, define a Vertex and an Edge : struct Ver...
5,056,549
5,059,306
Large Dynamic MultiDimensional Array Not Working
My code that I have is quite large and complicated so I won't waste your time reading it, but you're going to have to make certain assumtions about variables in it as a result. I will tell you the values of the variables which I have confirmed in the debugger so you know with certainty. Know that I have omitted a lot o...
Not sure why this didn't occur to me last night, but I was pretty tired. Heres what I decided to do: struct AbilityData { // Stuff CUtlMap<char*,int> ExtraData [MAX_ABILITY_LEVELS]; char **DataKeys; } Thats what my abilityData struct now looks like, and it now works, but now I want to reorganize it to be like: ...
5,056,606
5,099,428
How to use autotools to build Python interface at same time as library
I currently have a library written in C++, building with the GNU autotools, and I'd like to add a Python interface to it. Using SWIG I have developed the interface, but I'm having some trouble figuring out how integrate compilation of the Python module in with the rest of the process. I have looked into AM_PATH_PYTHON...
To find the include path, I'd use python-config. The trick is to use the python-config corresponding to the python installed in $PYTHON. AM_PATH_PYTHON AC_ARG_VAR([PYTHON_INCLUDE], [Include flags for python, bypassing python-config]) AC_ARG_VAR([PYTHON_CONFIG], [Path to python-config]) AS_IF([test -z "$PYTHON_INCLUDE"...
5,056,645
5,056,797
Sorting std::map using value
I need to sort an std::map by value rather than by key. Is there an easy way to do it? I got one solution from the follwing thread: std::map sort by data? Is there a better solution? map<long, double> testMap; // some code to generate the values in the map. sort(testMap.begin(), testMap.end()); // is there any func...
Even though correct answers have already been posted, I thought I'd add a demo of how you can do this cleanly: template<typename A, typename B> std::pair<B,A> flip_pair(const std::pair<A,B> &p) { return std::pair<B,A>(p.second, p.first); } template<typename A, typename B> std::multimap<B,A> flip_map(const std::map...
5,056,664
5,056,695
Get the type of the template parameter from an object, C++
Here is my simplified data structure: Object1.h template <class T> class Object1 { private: T a1; T a2; public: T getA1() {return a1;} }; Object2.h template <class T> class Object2: public Object1 <T> { private: T b1; T b2; public: T getB1() {return b1;} } Is there any way to ...
Add a using or typedef statement, like this: template <class T> class Object1 { private: T a1; T a2; public: T getA1() const {return a1;} using type = T; // or typedef T type; }; template <class Object> void foo(Object *o1, Object *o2) { typename Object::type x = o1->getA1(); // ... } ...
5,056,853
5,056,885
How to initialize an array of pointers to a struct in C++?
UPDATE : Answer at the bottom. Hi Guys, How to initialize an 'array of pointers to a struct' ? The catch is, the array is a member variable and the size passed to the declaration of the array in the constructor is variable entity. typedef struct Node { string key; int value; struct Node * l...
Variable-length arrays are not supported by the C++ standard. Instead, simply use a std::vector: private: std::vector<doubly *> table; ... myHashStrKey() : table(num_elements, NULL) // Initialises vector { ... }
5,056,958
5,056,993
Is there a way to substitute long namespaces with #define?
Suppose I have a very long namespace, which I don't want to type in all the time. But I don't want to use using namespace ... either. Can I use #define for this? Example: #define glm::quat glm::gtc::quaternion class Camera { protected: glm::quat m_mRotation; }; I don't want to use the using, because the glm:: par...
you don't need a define, use a namespace alias: namespace glm_quat = glm::gtc::quaternion::quat; or if you want the alias to be really in the glm namespace, put it there: namespace glm { namespace quat = gtc::quaternion::quat; }
5,056,973
5,056,994
When do you prefer using std::list<T> instead of std::vector<T>?
I've never used std::list<T> myself. I was wondering when people use it when we already have std::vector<T> which is just like arrays with contiguous memory. std::vector seems like a perfect choice when we need sequential container! So my question is When exactly do you prefer std::list over std::vector? and why exact...
Lists are better for inserting or deleting anywhere in the middle, vectors are better for inserting at the end. Vectors are also better for accessing elements. This is an artefact of the way they're implemented. So, if a collection changes very little (compared to accesses) or the changes are concentrated at the end, I...
5,057,021
5,057,065
Why are C++ inline functions in the header?
NB This is not a question about how to use inline functions or how they work, more why they are done the way they are. The declaration of a class member function does not need to define a function as inline, it is only the actual implementation of the function. For example, in the header file: struct foo{ void bar...
The definition of an inline function doesn't have to be in a header file but, because of the one definition rule (ODR) for inline functions, an identical definition for the function must exist in every translation unit that uses it. The easiest way to achieve this is by putting the definition in a header file. If you w...
5,057,137
5,057,147
c++ loop while child is alive
After I fork in a c++ program. What is the syntax to run a while loop until the child process dies. int value = fork(); if( value = 0 ) { //do something } else { while(childIsAlive) { //do something } } the do somethings are independent.
int Stat; if (waitpid(PidOfChild, &Stat, WNOHANG) == PidOfChild) { if (WIFEXITED(Stat) || WIFSIGNALED(Stat)) { childAlive = false; } } waitpid wait's for a state change in waitpid. If it returns PidOfChild, there was a change, and Stat is updated. WIFEXITED(Stat) will be true if the child process exited normal...
5,057,268
5,057,342
Which Clang compiler should I download?
I want to install Clang compliler on my system. I went to this link, but so many download options out there confused me, as to which version should I download? I'm using Dell's laptop : Windows 7 Basic 64-bit. I've already installed MinGW version 4.5.0. I've also installed Visual Studio 2008 as well as 2010. What do y...
You can use Clang with Visual Studio or MinGW. The choice is yours. But you'll need an external linker to produce Windows executables (MSVS's link.exe or MinGW's ld.exe/g++.exe). If you want to use MinGW, download the next to last item (frontend binaries to mingw). You can also compile Clang/LLVM from source, for that ...
5,057,348
5,057,370
Converting html to plain text without parsing c++?
I want to remove all html tag from the text. But I don't want to parse whole document using any dom library because creating a dom tree will be overhead on the performance, as I don't care about the structure. Is there any fast and efficient way to convert html to plain text ?
If you don't need an in-memory DOM tree, use a parser with a SAX interface. Mind that some real-world HTML might need fault-tolerant parsing, though.
5,057,368
5,057,402
Precision problem with stringstream and double
Possible Duplicate: Why do I see a double variable initialized to some value like 21.4 as 21.399999618530273? Here is my code #include <sstream> #include <iomanip> #include <string> #include <iostream> int main(int ac, char **av) { if (ac > 1) { std::string input = av[1]; std::stringstream ss; ...
You can't handle "all double values" with arbitrary precision. In your case, you have about 15 decimal digits of precision. Write std::numeric_limits<double>::digits10 to the console and you'll see. Take a read through this guide to floating-point arithmetic.
5,057,382
5,057,446
What is the performance overhead of std::function?
I heard on a forum using std::function<> causes performance drop. Is it true? If true, is it a big performance drop?
You can find information from the boost's reference materials: How much overhead does a call through boost::function incur? and Performance This doesn't determine "yes or no" to boost function. The performance drop may be well acceptable given program's requirements. More often than not, parts of a program are not perf...
5,057,428
5,057,485
Converting uint to float in C++
I'm using ReadProcessMemory in order to get 4 bytes. The function allows me to represent this as an unsigned int. I wish to represent this as a float; or in other words use the byte representation of this uint for my float. I've tried casting and it does not seem to work. Example: byte representation: 94 4E 2D 43 uint:...
ReadProcessMemory() takes a pointer to void so it is up to you to point it at a float. float f; ReadProcessMemory(hProcess, lpBaseAdress, &f, sizeof(f), NULL); Note that this will break when sizeof(unsigned int) != sizeof(float). Casting won't work because it will take the value and not the representation of the inte...
5,057,522
5,060,149
boost::shared_?? for non-pointer resources
Basically i need to do reference counting on certain resources (like an integer index) that are not inmediately equivalent to a pointer/address semantic; basically i need to pass around the resource around, and call certain custom function when the count reaches zero. Also the way to read/write access to the resource i...
Here is a small example about the use of shared_ptr<void> as a counted handle. Preparing proper create/delete functions enables us to use shared_ptr<void> as any resource handle in a sense. However, as you can see, since this is weakly typed, the use of it causes us inconvenience in some degree...
5,057,562
5,057,675
How is make_heap in C++ implemented to have complexity of 3N?
I wonder what's the algorithm of make_heap in in C++ such that the complexity is 3*N? Only way I can think of to make a heap by inserting elements have complexity of O(N Log N). Thanks a lot!
You represent the heap as an array. The two elements below the i'th element are at positions 2*i+1 and 2*i+2. If the array has n elements then, starting from the end, take each element, and let it "fall" to the right place in the heap. This is O(n) to run. Why? Well for n/2 of the elements there are no children. F...
5,057,596
5,057,926
Convert RFC 822 timestamp to unixtime, timezone values not working , C/C++
I've a function which converts an RFC 822 timestamp to unixtime #include <stdio.h> #include <time.h> int main() { struct tm tm; time_t unixtime; strptime("Sun, 20 Feb 2011 10:28:02 +0800","%a, %e %h %Y %H:%M:%S %z",&tm); unixtime = mktime(&tm); printf("%d\n",unixtime); return 0; } Problem: The timezone part (%z) ...
struct tm does not contain a timezone field. %z is supported simply to support the same flags as strftime. You'll need to extract and adjust the timezone offset manually.
5,057,614
5,064,073
Is reinterpret_cast mostly useless?
I've read various previous questions about the use of reinterpret_cast, and I've also read the relevant wording in the C++ standard. Essentially, what it comes down to is that the result of a pointer-to-pointer reinterpret_cast operation can't safely be used for anything other than being cast back to the original poin...
there's no guarantee that a reinterpret_cast from char* to unsigned char* won't crash your program when you try to dereference the unsigned char* pointer. You can't do such a cast in any other way, so you have to have to trust what your compiler does with this completely reasonable cast. Since reinterpret_cast doesn...
5,057,907
5,058,151
A way of allocating multidimensional arrays dynamically
salute.. I am learning dynamic allocations for multidimensional arrays in a book and I found some ways for that, And now haven't problem in it. But the author of the book shows us a way, but it doesn't work correctly. It is this: pbeans = new double [3][4]; // Allocate memory for a 3x4 array And this is the er...
This is covered in my FAQ on arrays: double (*pbeans)[4]; pbeans = new double[3][4]; // ... delete[] pbeans; For the "C declarator impaired", you could make that more readable with a typedef: typedef double row[4]; row *pbeans; pbeans = new row[3]; // ... delete[] pbeans; But in C++, we prefer RAII containers ov...
5,057,922
5,058,094
std::map: is find(key)->second faster than the [] operator?
std::map<long, double> x; x[5] = 1.2; double y = x[5]; double z = x.find(5)->second; Will one of these 2 assignments execute faster than the other? (supposing that the requested key is always present in the map) Is there any overhead associated with the dereferencing of the iterator when doing x.find(5)->second ? EDI...
Took this straight from <map>: mapped_type& operator[](const key_type& _Keyval) { // find element matching _Keyval or insert with default mapped iterator _Where = this->lower_bound(_Keyval); if (_Where == this->end() || this->comp(_Keyval, this->_Key(_Where._Mynode()))) _Where = this->inse...
5,057,987
5,058,021
What's the point of const void?
Apparently, it is possible to declare a function returning const void: const void foo() { } g++ seems to consider the const important, because the following code does not compile: #include <type_traits> static_assert(std::is_same<void(), const void()>::value, "const matters"); So does const void have any practical s...
Not really. But to ignore cv-qualifications on void or to make them errors could create unnecessary complexity in terms of both compiler implementation and end-user code. Consider templates like template<typename T> const T ... There's no reason to make using void in that scenario a special case (more than it alr...
5,058,014
5,058,045
Construction of object with non-default constructor inside C++ class
Iam new to C++ and below mentioned is the summary of the problem. Bar's constructor needs to explicitly call foo's constructor and the argument to foo's constructor has to be an object to baz, which has a default constructor. Iam not allowed to use new operator(dynamic allocation) to achieve this. I tried the below co...
Bar() : Foo(y) { }; What are you doing here? Foo is not a member of Bar. It's a type. x is a member of type Foo. But even if you write x(y), there is a problem in the order of initialization. As x is depending on y, so y must be initialized before x. So declare y before x to ensure the correct initialization! I would ...
5,058,031
5,058,370
Is there a tool for Visual C++ or other IDE, that would allow more than 1 programmer (online), to work on the same project, at the same time?
So is there a way I can share whole environment, edit, compile and execute my code in one mutual window with my friend-programmer being 200 miles away from me ? For example, I start an online session, my friend joins it and his IDE synchronizes all settings and project/source files for this session with mine, so we can...
Collaborative development is normally done through a software configuration management or version control system such as Subversion, PVCS, StarTeam, MKS, SourceSafe, CVS or any number of other options of varying cost and sophistication. The way this typically works is that each developer checks out the code and proje...
5,058,032
5,058,096
Having trouble setting headers in a QNetworkRequest
I am using the following function to make a post request: bool NewAccountDialog::verifyAccount() { QString loginURL = "https://accounts.craigslist.org/"; QString USERAGENT = "Mozilla/Firefox 3.6.12"; // This is all bullshit QNetworkAccessManager *manager = new QNetworkAccessManager(this); QNetwork...
The problem is in the second parameter (USERAGENT). A QByteArray can be constructed from a char array, but not from a QString (see QByteArray's documentation). You need either to use QString::toAscii(), QString::toLatin1() or something similar, or to make USERAGENT a char*: const char* USERAGENT = "Mozilla/Firefox 3.6...
5,058,222
5,058,312
Number of digits of GMP integer
Is there an easy way to determine the number of digits a GMP integer has? I know you can determine it through a log, but I was wondering if there was something built into the library that I'm missing. The only thing I've found in the manual is: _mp_size The number of limbs, or the negative of that when representing a n...
You can use size_t mpz_sizeinbase (mpz_t op, int base) to get the number of characters to output the number as a string in a specific base. size_t mpz_sizeinbase (mpz_t op, int base) Return the size of op measured in number of digits in the given base. base can vary from 2 to 62. The sign of op is ignored, just the ab...
5,058,349
5,058,365
Is it safe to use the "this" pointer in an initialization list?
I have two classes with a parent-child relationship (the Parent class "has-a" Child class), and the Child class has a pointer back to the Parent. It would be nice to initialize the parent pointer upon construction of the child, as follows: class Child; class Parent; class Child { public: Child (Parent* parent_ptr_) :...
Yes. It's safe to use this pointer in initialization-list as long as it's not being used to access uninitialized members or virtual functions, directly or indirectly, as the object is not yet fully constructed. The object child can store the this pointer of Parent for later use!
5,058,363
5,058,397
C++ error: 'Line2' has not been declared
C:\CodeBlocks\kool\praks2\src..\include\circle2.h|8|error: 'Line2' does not name a type| C:\CodeBlocks\kool\praks2\src..\include\circle2.h|17|error: 'Line2' has not been declared| ||=== Build finished: 2 errors, 0 warnings ===| circle2.h : #ifndef CIRCLE2_H #define CIRCLE2_H #include "geometry.h" class C...
you can try to add: class Line2; before the class Circle2 {
5,058,443
5,058,751
C++: how to compare several vectors, then make a new sorted vector that contains ALL elements of all vectors
Update: I have a couple of what are probably silly questions about commenter 6502's answer (below). If anyone could help, I'd really appreciate it. 1) I understand that data 1 and data 2 are the maps, but I don't understand what allkeys is for. Can anyone explain? 2) I know that: data1[vector1[i].name] = vector1[...
The algorithm you are looking for is usually named "merging". Basically you sort the two data sets and then look at data in pairs: if the keys are equal then you process and output the pair, otherwise you process and advance only the smallest one. You must also handle the case where one of the two lists ends before the...
5,058,506
5,058,594
maintaining a recursion count
I'm trying to count the number of calls within a recursive permutation function. I've written a function that fills a queue with all the permutations but I can't seem to figure out how to maintain an accurate count. Ultimately i'd like the function to return a subset of the permuatations specified by lbound and ubound...
int foo(int count,/*Other Params*/) { /*Calucation*/ if (!terminatingCondition) { foo(count++,/*Other Params*/); } logger.log("foo was called " + count + "times"); return /*calcualtion*/; }
5,058,543
5,060,167
SendMessageCallback usage example
http://msdn.microsoft.com/en-us/library/ms644951%28v=VS.85%29.aspx I v been searching everywhere but cant find a single working thing in c on how this could be done. There seems to be several calls which totally confused me. Perhaps someone can put just a small example on how to declare this callback then post message ...
I assume that you are perfectly comfortable with plain ol' SendMessage. The step from there to SendMessageCallback is not that long. First, look at LRESULT WINAPI SendMessage(__in HWND hWnd, __in UINT Msg, __in WPARAM wParam, __in LPAR...
5,058,568
5,058,613
Redirecting C++ streams
I have a method search that I want to feed an input stream and then put output on an output stream. void search(std::istream & is, std::ostream & os); For now I'd like to do this with cin/cout. From the command prompt: a.out < input_file.txt In main, I try to do this by passing cin/cout to the search() method. X.sea...
This compiles and runs fine for me in xcode (c++ cmdline new project wizard), looks like you're missing an #include <iostream> or main, or a definition of your X class. #include <iostream> void foo( std::istream &is, std::ostream &os ) { std::string s; while ( getline( is, s, '\n' ) ) { os << s; ...
5,058,584
5,058,703
Unreferenced external symbol during DLL function call
I'm having problems in implementing a class in a DLL in the same way it is explained here . I have my interface with all the methods declared as virtual, I have my class that implements the interface and I have the method that should create the object of the class. The problem is here, when I try to use it I get a "unr...
If you've correctly defined the function in the DLL, and it is exported properly, then the only plausible explanation is that there is something wrong with your use of the .lib file in the application that uses the DLL.
5,058,665
5,058,948
How do I use CIN to read values from a file (64 bit integer)
Let's say I have the file input.txt containing the following numbers : 2 1 1 888450282 1 2 I need to read the first line in separate variables (a,b,c,d). The big value can be big like a 64 bit integer. How do I use C++ IO to do this? And the second line can have 1 to N values. Normally I do this in C but I want to lea...
If you are only concerned about the first line of the file you can use something like the following to get it. #include <fstream> #include <iostream> And the following code will handle the file. ifstream file("yourfile.txt", ios::in); int a, b, c; long long d; file >> a >> b >> c >> d; printf("a:...
5,058,676
5,058,899
std::string implementation in GCC and its memory overhead for short strings
I am currently working on an application for a low-memory platform that requires an std::set of many short strings (>100,000 strings of 4-16 characters each). I recently transitioned this set from std::string to const char * to save memory and I was wondering whether I was really avoiding all that much overhead per str...
Well, at least with GCC 4.4.5, which is what I have handy on this machine, std::string is a typdef for std::basic_string<char>, and basic_string is defined in /usr/include/c++/4.4.5/bits/basic_string.h. There's a lot of indirection in that file, but what it comes down to is that nonempty std::strings store a pointer to...
5,058,711
5,058,756
trying to initiate a class with a constructor that takes an argument
class token { private: char m_chIcon; //actual ascii char that shows up for this token location m_cPlayerLocation; // every token has a location token() {} public: token(char icon) : m_chIcon(icon) {} }; class board { private: token m_cPlayer('@'); }; I have tried with and with...
Member variables in C++03 can only be initialized inside a function (e.g. from a constructor): class board { private: token m_cPlayer; public: board() : m_cPlayer('@') {} };
5,058,735
5,058,770
Getting lots of undefined references when using QtNetwork components
#include "QtGui" #include "QtNetwork/QtNetwork" #include "QtNetwork/qnetworkaccessmanager.h" #include "QtNetwork/qnetworkrequest.h" #include "QtNetwork/QNetworkAccessManager" #include "QtNetwork/QNetworkRequest" ...... bool NewAccountDialog::verifyAccount() { QString loginURL = "https://accounts.craigslist.org/";...
You need to link against module network. To do that add to .pro file QT += network Check http://doc.qt.io/qt-4.8/qtnetwork-module.html#details for reference.
5,058,814
5,087,816
How to add the common navigation bar to a Meego app?
When using the Meego Touch Framework, the standard MApplicationWindow has the common navigation bar (with the switcher, menu and close buttons) already attached. For example, the following code: #include <MApplication> #include <MApplicationWindow> int main(int argc, char *argv[]){ MApplication app(argc, argv); ...
How I would implement this, would probably be a fixed height, variable width QHBoxLayout with a stretch factor for those indices that need it. Then I would just use QPushButton and QCombobBox for the widgets and finish them off with a custom stylesheet and icons. I would then wrap these inside a neat little custom widg...
5,058,831
5,058,877
How to Convert beween Stack and Heap Objects
Example: Class *_obj1; Class *_obj2; void doThis(Class *obj) {} void create() { Class *obj1 = new Class(); Class obj2; doThis(obj1); doThis(&obj2); _obj1 = obj1; _obj2 = &obj2; } int main (int argc, const char * argv[]) { create(); _obj1->doSomething(); _obj2->doSomething(); ...
So, the first question is: if how can I convert the stack object (obj2) to a heap object so it's not deallocated after create() exits? I want a straight answer, The straight answer is: You can't "convert" an object between the stack and heap. You can create a copy of the object that lives in the other space, as othe...
5,058,852
5,059,247
LNK 2005 in Visual C++ in Visual Studio 2010
I'm trying to compile a C++ program, written using Visual C++ 2005 and MFC, in MS VS 2010. Sadly I'm getting the following error during compilation: Error 2 error LNK2005: "public: virtual __thiscall CMemDC::~CMemDC(void)" (??1CMemDC@@UAE@XZ) already defined in CMemDCImpl.obj Project\Project\Project\uafxcwd.lib(afxglob...
You mention that you CMemDCImpl is defined in a cpp file. However, it also seems to be defined in uafxcwd.lib (a library you apparently use). I can think of two possibilities for this error: You're including the cpp of the library you're attempting to use. Usually, when you use a precompiled library, you only need to...
5,059,049
5,059,112
Read a string line by line using c++
I have a std::string with multiple lines and I need to read it line by line. Please show me how to do it with a small example. Ex: I have a string string h; h will be: Hello there. How are you today? I am fine, thank you. I need to extract Hello there., How are you today?, and I am fine, thank you. somehow.
#include <sstream> #include <iostream> int main() { std::istringstream f("line1\nline2\nline3"); std::string line; while (std::getline(f, line)) { std::cout << line << std::endl; } }
5,059,423
5,059,433
Arithmetic with void pointers in C++
I need to access an object in a buffer, pointed by a void pointer. The object is located at a certain offset but since arithmetic on a void pointer is prohibited how can I access the object?
You can cast the pointer to char* (+1 on such pointer is offset by one byte) or any other pointer type if that suits your needs better. However, this approach is grossly error prone! You better check your design, something smells here! void* are in 99% of cases unnecessary in C++, designs that use them are usually more...
5,059,471
5,059,494
using per class boost::log::sources::logger from const member function
I want a log source per class like the basic_logger example from the docs This works but I get a compiler error complaining about the constness when logging something from a const member function like so: #include "boost/log/sources/channel_logger.hpp" #include "boost/log/common.hpp" #include "boost/log/utility/init/to...
If the log is stored in the class, then of course you cannot modify it in a const context. I realise that you asked for something else, but I honestly think that mutable is the appropriate solution here. This is exactly the use case that is why mutable exists.
5,059,513
5,059,566
whats wrong with my c++ regex match
i am writing an robots.txt parser in c++ boost::regex exrp( "^User-agent:\s*(.*)"); boost:: match_results<string::const_iterator> what; if(boost::regex_search( robots, what, exrp ) ) { string s( what[1].first, what[1].second ); ...
You need the double backslash '\\' if you don't use c++0x raw strings.
5,059,613
5,060,476
Syntax Error in dialog resource
I have a Win32 GUI application and in my resource.rc file I'm trying to create a dialog, but I get a syntax error in my code. IDD_ABOUT DIALOG 0, 0, 239, 66 STYLE DS_MODALFRAME | WS_CAPTION | WS_POPUP | WS_SYSMENU // error here CAPTION "About" FONT 8, "MS Sans Serif" BEGIN DEFPUSHBUTTON "&OK", IDOK, 174, 27, 50, 14 ...
Please forgive me if this is an irrelevant pointing out. I think STYLE's argument values like window style(WS_...) and dialog box style(DS_...) are defined in a system header file. So, probably <windows.h> or similar header file has to be #includeed before the use of those values. Hope this helps.
5,059,744
5,059,784
Does a simple cast to perform a raw copy of a variable break strict aliasing?
I've been reading about strict aliasing quite a lot lately. The C/C++ standards say that the following code is invalid (undefined behavior to be correct), since the compiler might have the value of a cached somewhere and would not recognize that it needs to update the value when I update b; float *a; ... int *b = reint...
If you want to copy some memory, you could just tell the compiler to do that: Edit: added a function for more readable code: #include <iostream> using std::cout; using std::endl; #include <string.h> template <class T, class U> T memcpy(const U& source) { T temp; memcpy(&temp, &source, sizeof(temp)); return...
5,059,938
5,059,966
Time delay in method delaying whole program
I have two methods, for example, delayloop() and function(), where delayloop() has a while and time() delay to loop it every n seconds. If in my main, I call: delayloop(); then function(); The method function() is never called, as the looping method before it seems to prevents it. What is the method to prevent the ap...
Under normal conditions, control flows sequentially through your program. If you enter an endless loop before the function() line, then function is never going to get called. So it would seem you have an error in the delayloop function, and it would help is if we could see the code. There we have it. You never set dela...
5,059,973
5,061,643
error linking with sdl while crosscompiling application for ARM
I'm trying to crosscompile simple SDL application for ARM processor. I'm using Motorola A1200 with Intel Xscale PX27x rev 7 (with iwmmxt extension) processor And modified crosscompiling toolchain with for example, gcc: arm-linux-gnu-g++ --version arm-linux-gnu-g++ (GCC) 3.3.6 Copyright (C) 2003 Free Software Foundatio...
-L just adds a library search directory. Try also specifying -lSDL-1.2 or -lSDL to actually link against a library.
5,059,999
5,060,026
C++: "const" in front of a class method
Taking for example this method declaration: const Vector Vector::operator - ( const Vector& other ) const; I know that the second const makes the Vector passed as an argument immutable, and that the last const declares that the method does not change the current instance of the Vector class.... But what exactly does ...
It is an outdated security measure to prevent nonsense code like a - b = c to compile. (I say "outdated" because it prevents move semantics which only works with non-const rvalues.)
5,060,177
5,060,234
c++ casting a union to one of its member types
The following seems perfectly logical to me, but isn't valid c++. A union cannot be implicitly cast to one of it's member types. Anyone know a good reason why not? union u { int i; char c; } function f(int i) { } int main() { u v; v.i = 6; f(v); } And can anyone suggest a clean alternative (the cleanest I ca...
While agreeing with Crazy Eddie that it doesn't look that better to me you can actually get an implicit conversion by defining it: union u { int i; char c; operator int () const { return i; } operator char () const { return c; } };
5,060,365
5,060,396
How does a program manage type information?
I was just wondering, how is the type information managed internaly by a c++ program? eg. float f; needs 32bits of memory. But since all bits are used to save the value, how does the program remember it to be of the type float? (I know this is quite a noob question...)
You need to differentiate between static (compile-time) type and dynamic (run-time) type. Static types are managed by the compiler during compilation and, except for the type-specific semantics embedded in the resulting code, forgotten at run-time. Dynamic type information is usually held in so-called type-specific "...
5,060,376
5,060,676
AES 128bit, 192bit, 256bit
I've managed successfully to write my own AES implementation using a 128bit key. However I'm still dangled how to interpret the AddRoundKey function using 192bit and 256bit keys. Some facts: Block is 128 bits (State) Rounds 128bit = 10, 192bit = 12, 256bit = 14 Nk 128bit = 4 (equal to Block size), 192bit = 6, 256bit =...
I think you've got things slightly confused. From FIPS-197: In the AddRoundKey() transformation, a Round Key is added to the State by a simple bitwise XOR operation. Each Round Key consists of Nb words from the key schedule So the AddRoundKey() function xor's the state with the appropriate word from the key schedul...
5,060,561
5,060,617
out put of the cross product
i am trying to get the 'cross product' of two vectors. these two vectors represent two planes. so, my vectors are as a1,b1,-1 and a2,b2,-1. (I used, my plane equation as ax+by-z+d=0). this was my defined function to get the cross product; vector<double> cross_vector(vector<double> plane1,vector<double> plane2){ vector<...
The math looks correct. Placing a quick A = <1,0,0> and B = <0, 1, 0> gave a reasonable result on the backside of <0, 0, 1>. The e notatin represent the number times 10 to the power after the e. So those might be reasonable as well, but it's hard to say as from your example I can't tell what your input values were. ...
5,060,604
5,122,391
Window title truncation when using Window::set_title with gtkmm
I am trying to rename the title of my application's main window, but when trying so, the name get truncated. I tried to see if it was a conversion problem but I realy can't find why this happen. Try this little program. Hit cancel to see the default application name in the title bar, but if you choose a file, it should...
OK I finally found the solution myself. I write it here in case someone else gets the same issue. I don't know if it is a bug or what, but seems like GTK substitutes the three last characters before a '\n' to '...'. In other words, the string used to rename the window must not contain any '\n' or else set_title will no...
5,060,607
5,060,679
CSV Parser works in windows, not linux
I'm parsing a CSV file that looks like this: E1,E2,E7,E8,,, E2,E1,E3,,,, E3,E2,E8,,, E4,E5,E8,E11,,, I store the first entry in each line in a string, and the rest go in a vector of strings: while (getline(file_input, line)) { stringstream tokenizer; tokenizer << line; getline(tokenizer, roomID, ','); ...
I suspect that the \r in the windows \r\n linefeed could mess up the code doing your printing. If you change to this if statement, does the problem disappear? if (!adjRoomID.empty() && (adjRoomID[0] != '\r')) EDIT: Fixed typo
5,060,786
5,061,487
Using decltype in a late specified return in CRTP base class
I'm trying to use decltype in the late specified return of a member function in a CRTP base class and it's erroring with: invalid use of incomplete type const struct AnyOp<main()::<lambda(int)> >. template<class Op> struct Operation { template<class Foo> auto operator()(const Foo &foo) const -> typename...
You are, as another answer describes already, trying to access a member of a class in one of the class' base class. That's going to fail because the member is yet undeclared at that point. When it instantiates the base class, it instantiates all its member declarations, so it needs to know the return type. You can make...
5,060,789
5,988,959
is it possible to reclaim memory resources from a llvmContext?
since llvm 2.7, it is possible to isolate Types and anything that LLVM might need to create a JIT module inside a llvmContext however, i am not entirely clear how to reclaim memory resources internally allocated in a llvmContext once it has been used. I think there should be one since the point of using llvmContext is ...
Yes, LLVMContext's destructor will free all its memory. If it's not, please file a bug, http://llvm.org/bugs ! Of course, don't destruct the global one :-) If you're shutting down, you can also call llvm::llvm_shutdown() which frees global static variables. Note that there's no llvm_startup function or anything like th...
5,060,879
5,061,030
reinterpret_cast for almost pod data (is layout-compatibility enough)
I am trying to learn about static_cast and reinterpret_cast. If I am correct the standard (9.2.18) says that reinterpret_cast for pod data is safe: A pointer to a POD-struct object, suitably converted using a reinterpret_cast, points to its initial member (or if that member is a bit-field, then to the unit in ...
I believe the following are valid because complex_base is POD You are wrong. d[0] does not refer to the first member of a complex_base object. Its alignment may therefor not be good enough for a complex_base object, therefor such a cast is not safe (and not allowed by the text you quote). Does the following complet...
5,060,996
5,061,066
Why is creating STL containers dynamically considered bad practice?
Title says it. Sample of bad practive: std::vector<Point>* FindPoints() { std::vector<Point>* result = new std::vector<Point>(); //... return result; } What's wrong with it if I delete that vector later? I mostly program in C#, so this problem is not very clear for me in C++ context.
As a rule of thumb, you don't do this because the less you allocate on the heap, the less you risk leaking memory. :) std::vector is useful also because it automatically manages the memory used for the vector in RAII fashion; by allocating it on the heap now you require an explicit deallocation (with delete result) to ...
5,061,188
5,061,669
Creating a queue of queue of custom defined objects (using a custom defined queue template)
I am using the following code to construct a queue of 10 queues, each containing 10 person objects consisting of three member variabless. Every member variable is different from the others. Later on, I cycle through the queues using a pair of nested for loops to print out all the attributes, however when I do so, rathe...
You're going to run into all sorts of trouble having queue of queue because queue doesn't implement its copy and assign semantics properly. Whenever you copy you will be copying the pointer you allocated and then your temporary will be deleted taking the pointer with it, leaving the copy with a dangling pointer. That y...
5,061,275
5,061,364
Binding rvalue to non-const reference via pointer cast?
I don't understand how the following code compiles/doesn't compile: struct Temp { int i; }; int main(int argc, char * argv[]) { //Temp &ref1 = (Temp){42}; // Error, as expected Temp &ref2 = *(Temp*)&(Temp){42}; // A-OK std::cerr << ref2.i << std::endl; return 0; } I'm using g++ 4.4.4.
Your code is not really C++. It uses a compound literal which is a C99 feature. In C99 it evaluates to an lvalue and taking the address of the literal is completely fine there. Integrating this extension into C++, GCC appears to change the rule of it and make it an rvalue, better fitting the classification of them into...
5,061,465
5,061,633
c++ variable array reservation problem
I have a problem caused when reserving array. The problem is a heap error. The software i am making is like that: I am making a small software to render a model of a specific format. the model contains several groups and every group contains array vertices and array of indices for these verts "such as a motorcycle mode...
You don't supply enough info to pintpoint the problem, or even what the problem is. But there are things you can do to clean up the code, and maybe that will help.     1. Use std::vector instead of `new`-ing raw arrays Instead of unsigned int *m_pIndices=new unsigned int[index]; use std::vector<unsigned> indices( ind...
5,061,518
5,061,540
How to get the Type of c++0x lambda expression?
I want get the type of lambda as the template argument. How to do this? template<class T> class Foo { public: Foo(T t){ t(); } }; int main() { Foo< type?? > foo([](){ cout<<"construct OK"; }); system("pause"); return 0; }
It's possible to deduce the type of a lambda-expression when it is the argument to a function template function parameter whose type is deduced. Lambda expressions however are explicitly forbidden to appear inside an unevaluated operand --- this includes decltype. It was found that this includes several yet unhandled ...