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
1,349,530
1,349,781
Loader lock (regsvr32 R6033 error) with managed C++ dll
I have a C++ dll which implements several COM interfaces, that I'm trying to migrate to managed C++. I set the /clr compiler flag and changed the Runtime Library property from /MT to /MD to avoid the conflict between these two flags, but that's all I've changed. When it attempts to register the dll during the build process, I get the following error: R6033 - Attempt to use MSIL code from this assembly during native code initialization This indicates a bug in your application. It is most likely the result of calling an MSIL-compiled (/clr) function from a native constructor or from DllMain. I read about Loader Lock and can't figure it out - I have not added a single call to any managed code. Here's the entire body of the DllMain procedure: [Edit - per comment below, I added #pragma unmanaged to the top of the cpp file with no improvement. The Module init is all code contained in the ATL libraries from what I can tell.] extern "C" BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) { lpReserved; if (dwReason == DLL_PROCESS_ATTACH) { _Module.Init(ObjectMap, hInstance, &MYGUID); DisableThreadLibraryCalls(hInstance); } else if (dwReason == DLL_PROCESS_DETACH) _Module.Term(); return TRUE; // ok }
You need to add the /clr compiler flag only to the files that use managed code and not for the whole project. This is what the Visual Studio "Wizard" does, here is how I've tested: Create a Visual C++ ATL Project Added a ATL Simple Object, in order to have a COM interface (Project->Add Class) Added a CLR Component Class. The Wizard prompted me with "You are adding a CLR component to a native project. Your project will be converted to have Common Language Runtime support." Compile project, compiles fine and registers fine. Checked the project settings -> "No Common Language Runtime support" Checked the clrcomponennt.cpp settings -> "Common Language Runtime Support (/clr)" Opened the dll in OleView -> COM interface was present Opened the dll in Red Gate's .NET Reflector -> clrcomponent was present
1,349,734
1,349,748
Why would anyone use set instead of unordered_set?
C++0x is introducing unordered_set which is available in boost and many other places. What I understand is that unordered_set is hash table with O(1) lookup complexity. On the other hand, set is nothing but a tree with log(n) lookup complexity. Why on earth would anyone use set instead of unordered_set? i.e is there a need for set anymore?
When, for someone who wants to iterate over the items of the set, the order matters.
1,350,243
1,350,255
Why does the C++ ofstream write() method modify my raw data?
I have a jpeg image in a char[] buffer in memory, all I need to do is write it out to disk exactly as is. Right now I'm doing this ofstream ofs; ofs.open(filename); ofs.write(buffer, bufferLen); ofs.close(); but the image doesn't come out right, it looks garbled with random black and white stripes everywhere. After comparing the image with the original in a hex viewer, I found out that the ofstream is modifying the data when it thinks I'm writing a newline character. Anyplace that 0x0A shows up in the original, the ofstream writes as two bytes: 0x0D0A. I have to assume the ofstream is intending to convert from LF only to CRLF, is there a standard way to get it to not do this?
Set the mode to binary when you open the file: http://www.cplusplus.com/reference/iostream/ofstream/ofstream/
1,350,271
1,350,285
In C++ how to return index of an array if user entered matches entered array?
I wanted to know how can we get the index of the array if the user entered array matches the input array ? For example: Input Array = [1,2,3,4] and user entered Array = [2,3] than I should get output as index where both array matches is 1. Guidance would be highly appreciated.
Use the STL search algorithm, which does just what you want: "The search() algorithm looks for the elements [start2,end2) in the range [start1,end1)." You'll need to supply it pointers to the start and end of the two arrays; you get the end pointer for an array by adding its length to its start pointer. Better, use the STL vector to store your data instead of an array, and then you can just call vec.begin() and vec.end() to get the iterators you want. Edit: To do it without std::search, follow the example on the link I provided, which shows how search can be done. If you're doing it C-style, you'll use pointers (like int*) rather than ForwardIterator. The only tricky bit there is the part outside the loop, where they figure out what limit should be set to - this will turn into some pointer arithmetic.
1,350,288
1,350,303
Static local in class member function survives class reallocation?
class Foo { public: void bar(); }; void Foo::bar() { static int n = 0; printf("%d\n", n++); } int main(int argc, char **argv) { Foo *f = new Foo(); f->bar(); delete f; f = new Foo(); f->bar(); delete f; return 0; } Does n reset to 0 after delete'ing and new'ing the class over again? Or is n effectively a static class member (same reference in all instances)? In other words, should I get 0 0 or 0 1 ?
As the variable is static in the function, it will be 0, 1 as the memory is not delete as it is static, even if the variable is part of a function and not part of the class. Even when you delete an instance of a class, the functions still remain in memory for the class as they can be used by other instances of the class.
1,350,380
1,350,411
problems using STL std::transform from cygwin g++
I am running g++(gcc version 3.4.4) on cygwin. I can't get this small snippet of code to compile. I included the appropriate headers. int main(){ std::string temp("asgfsgfafgwwffw"); std::transform(temp.begin(), temp.end(), temp.begin(), std::toupper); std::cout << "result:" << temp << std::endl; return 0; } I have not had any issues using STL containers such as vector. Does anyone have any suggestions or insights into this situation. Thanks.
This explains it quite well. Which will boil down to this code: std::transform(temp.begin(),temp.end(),temp.begin(),static_cast<int (*)(int)>(std::toupper));
1,350,396
1,350,407
Error while inserting pointer to a vector
I have the following CPP code snippet and the associated error message: Code snippet struct node{ char charVal; bool childNode; struct node *leftChild; struct node *rightChild; }; vector<std::pair<int,struct node*> > nodeCountList; struct node *nodePtr = new struct node; nodeCountList.push_back(1,nodePtr); Error message error: no matching function for call to ‘std::vector<std::pair<int, node*>, std::allocator<std::pair<int, node*> > >::push_back(int&, node*&)’ /usr/lib/gcc/i386-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_vector.h:602: note: candidates are: void std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = std::pair<int, node*>, _Alloc = std::allocator<std::pair<int, node*> >] Please help me troubleshoot the error message. cheers
You need to push a std::pair. nodeCountList.push_back(std::make_pair(1,nodePtr));
1,350,410
1,350,500
Have you heard of C++ Server Pages?
I have been looking for a ways to maximize speed in my web application. Came across an interesting application called CSP. Have you guys ever heard of them? They claim that you can program web application in c++. Is it worth it? http://www.micronovae.com/CSP.html
...Is it worth it? It depends on what you're trying to do. Most web applications are built with little or no regard for performance. The majority of pages do not need CGI at all. Using a database and code to produce/modify the page makes sense but serving pages to clients by generating each time is not optimum. As stated by others, creating the design, layout, content, infrastructure and keeping it all running usually take precedence over speed of generating the page. The current methods used for performance are reverse caching, edge side caching, load balancing, clustering, etc.. The web system is fed by a standard framework (java, php, python, ruby, perl, etc.) and the performance gains are met by spreading the load over more boxes and caching. Any CGI, even C++, will be slower than static files served by an optimized static server (ex. nginx) or static files served from memory using a reverse cache (ex. varnish). That being said most people shy away from using a lower level language for web serving because of lack of knowledge in lower level languages and the mass of code and frameworks available in scripting languages. Having worked on projects where management dictated that no open source code was to be used, I do not agree that it takes longer to develop using lower level languages. If you wrote "all" the code in PHP it would take you just as long but most don't. Most people use other's code and then claim it's faster than writing all your own code in a lower level language. Web apps usually are very simplistic and over time you (or your company) will develop a set of libraries to do standard web routines. Once written, a CGI web page can be constructed just as fast in C or C++ as in any scripting language. But if you need an json imported to your AJAX output chances are you'll find some amount of starter code in a scripting language rather than a lower level language. Are web apps built with C and C++? Absolutely. Many of those "evil" ad servers are coded in C for performance. Many web based "applications" are built using C or C++ such as VMware's web based virtual console. If you're looking for performance start thinking of your web application as two separate apps. One is a content management and page generator. The other is the serving framework. Full pages and page fragments can be pre-generated or generated on demand and served as static files increasing performance far above any changes in programming language. Even if a page only lasts for two requests it may be 100 to 1 load and speed difference. Dealing with sessions, authentication and authorization becomes the tricky part. How to de-couple sessions from pages and maintain security. This is often done by using C based modules in the web server. The same thing is done for SSL decryption, GZIP compression, flow control, etc.. If you're writing a web based game server or complex web app then by all means start building a C or C++ library. If you want to speed up a blog, learn and use clustering and caching techniques.
1,350,528
1,351,815
Initializing a vector with stream iterators
I'm trying to initialize a vector using iterators and I'm getting a compiler error basically saying that there's no matching function to call. The code reads from a file with an istream_iterator and ends with an input sentinel. Then I try to initialize the vector with those two iterators. #include "std_lib_facilities.h" #include<iterator> int main() { string from, to; // get source and target file names cin >> from >> to; ifstream is(from.c_str()); // open input stream ofstream os(to.c_str()); // open output stream istream_iterator<string> ii(is); // make input iterator for stream istream_iterator<string> eos; // input sentinel ostream_iterator<string> oo(os,"\n"); vector<string> words(ii, eos); // vector initialized from input sort(words.begin(), words.end()); // sort the buffer copy(words.begin(), words.end(), oo); // copy buffer to output } I know I could use the copy function to copy the input stream into the vector, but I read that it can be done this way as well. Can anyone explain why this is not compiling? Thanks. Compiler error: C:\Users\Alex\C++\stream_iterators.cpp|16|error: no matching function for call to `Vector<String>::Vector(std::istream_iterator<String, char, std::char_traits<char>, ptrdiff_t>&, std::istream_iterator<String, char, std::char_traits<char>, ptrdiff_t>&)'| Edit: It is not a header problem. Std_lib_facilities has all of the needed headers.
The book header had some kind of compliance issues, so I just included the appropriate headers and it worked.
1,350,532
1,350,807
Way to determine proper predicate for templated types
Suppose I have a function which looks like this: template <class In, class In2> void func(In first, In last, In2 first2); I would like this function to call another function which accepts a predicate. My initial instinct was to do something like this: template <class In, class In2> void func(In first, In last, In2 first2) { typedef typename std::iterator_traits<In>::value_type T; other_func(first, last, first2, std::less<T>()); } But there is a problem, what if In and In2 are iterators to different types? For example, char* vs int*. Depending on which is In and which is In2 the predicate may be truncating values during its comparison. For example, if In is char* then std::less<char> will be called even if In2 is an int*. When ::operator< is given two parameters, the compiler is able to deduce the correct type and the standard type promotion rules apply. However, when selecting a predicate to pass to a function, there is no oportunity to have this happen. Is there some clever way to figure out which version of std::less<> I want to pass based on In and In2? EDIT: The following example illustrates the problem: unsigned int x = 0x80000000; unsigned char y = 1; std::cout << std::less<unsigned char>()(x, y) << std::endl; std::cout << std::less<unsigned int>()(x, y) << std::endl; will output: 1 0 EDIT: After thinking about it, what I would really like is to be able to do something like this: typedef typeof(T1() < T2()) T; other_func(first, last, first2, std::less<T>()); I suppose I could use gcc's __typeof__ extension..., but I don't love that idea either. Any way to get that net effect in a standard conformant way?
I seemed to remember that there was a traits for this in boost, but I can't find it after a quick search. If you are no more successful than me, you can construct it yourself, template <typename T1, typename T2> struct least_common_promotion; template <> struct least_common_promotion<short, int> { typedef int type; }; but you'll have to specify quite a few explicit specializations. The type traits library of boost can perhaps help you reduce their number. Edit: I feel stupid, such kind of things are needed for operation (where the result type depend on the operands types), but not for predicates (where the result type is bool). You can simply write: template <class T1, T2> struct unhomogenous_less : public std::binary_function<T1, T2, bool> { bool operator()(T1 const& l, T2 const& r) const { return l < r; } }; ... typedef typename std::iterator_traits<In>::value_type value_type_1; typedef typename std::iterator_traits<In2>::value_type value_type_2; other_func(first, last, first2, unhomogenous_less<value_type_1, value_type_2>());
1,350,593
1,350,916
Finding the Difference between the contents in two Files
I am developing a Application which takes two Files and output will be two files which will have only the contents which differs in both the files. The application is developed using VC++ My Files are of Html type Is there any library which will do the diff opereation between two files
WinMerge is a Windows differencing and merging tool. It uses diffutils, written using VC++, and it's open source.
1,350,657
1,350,946
variable parameter function, how to make it type safe and more meaningful?
I am a newer for C++, and my first language is Chinese, so my words with English may be unmeaningful, say sorry first. I know there is a way to write a function with variable parameters which number or type maybe different each calling, we can use the macros of va_list,va_start and va_end. But as everyone know, it is the C style. When we use the macros, we will lose the benefit of type-safe and auto-inference, then I try do it whit C++ template. My work is followed: #include<iostream> #include<vector> #include<boost/any.hpp> struct Argument { typedef boost::bad_any_cast bad_cast; template<typename Type> Argument& operator,(const Type& v) { boost::any a(v); _args.push_back(a); return *this; } size_t size() const { return _args.size(); } template<typename Type> Type value(size_t n) const { return boost::any_cast<Type>(_args[n]); } template<typename Type> const Type* piont(size_t n) const { return boost::any_cast<Type>(&_args[n]); } private: std::vector<boost::any> _args; }; int sum(const Argument& arg) { int sum=0; for(size_t s=0; s<arg.size(); ++s) { sum += arg.value<int>(s); } return sum; } int main() { std::cout << sum((Argument(), 1, 3, 4, 5)) << std::endl; return 0; } I think it's ugly, I want to there is a way to do better? Thanks, and sorry for language errors.
You can do something like this: template <typename T> class sum{ T value; public: sum () : value() {}; // Add one argument sum<T>& operator<<(T const& x) { value += x; return *this; } // to get funal value operator T() { return value;} // need another type that's handled differently? Sure! sum<T>& operator<<(double const& x) { value += 100*int(x); return *this; } }; #include <iostream> int main() { std::cout << (sum<int>() << 5 << 1 << 1.5 << 19) << "\n"; return 0; } Such technique (operator overloading and stream-like function class) may solve different problems with variable arguments, not only this one. For example: create_window() << window::caption - "Hey" << window::width - 5; // height of the window and its other parameters are not set here and use default values
1,350,819
1,350,833
C++, Free-Store vs Heap
Dynamic allocations with new/delete are said to take place on the free-store,while malloc/free operations use the heap. I'd like to know if there is an actual difference, in practice. Do compilers make a distinction between the two terms? (Free store and Heap, not new/malloc)
See http://www.gotw.ca/gotw/009.htm; it can describe the differences between the heap and the free-store far better than I could: Free-store: The free store is one of the two dynamic memory areas, allocated/freed by new/delete. Object lifetime can be less than the time the storage is allocated; that is, free store objects can have memory allocated without being immediately initialized, and can be destroyed without the memory being immediately deallocated. During the period when the storage is allocated but outside the object's lifetime, the storage may be accessed and manipulated through a void* but none of the proto-object's nonstatic members or member functions may be accessed, have their addresses taken, or be otherwise manipulated. Heap: The heap is the other dynamic memory area, allocated/freed by malloc/free and their variants. Note that while the default global new and delete might be implemented in terms of malloc and free by a particular compiler, the heap is not the same as free store and memory allocated in one area cannot be safely deallocated in the other. Memory allocated from the heap can be used for objects of class type by placement-new construction and explicit destruction. If so used, the notes about free store object lifetime apply similarly here.
1,350,994
1,351,902
Is it safe to read an integer variable that's being concurrently modified without locking?
Suppose that I have an integer variable in a class, and this variable may be concurrently modified by other threads. Writes are protected by a mutex. Do I need to protect reads too? I've heard that there are some hardware architectures on which, if one thread modifies a variable, and another thread reads it, then the read result will be garbage; in this case I do need to protect reads. I've never seen such architectures though. This question assumes that a single transaction only consists of updating a single integer variable so I'm not worried about the states of any other variables that might also be involved in a transaction.
atomic read As said before, it's platform dependent. On x86, the value must be aligned on a 4 byte boundary. Generally for most platforms, the read must execute in a single CPU instruction. optimizer caching The optimizer doesn't know you are reading a value modified by a different thread. declaring the value volatile helps with that: the optimizer will issue a memory read / write for every access, instead of trying to keep the value cached in a register. CPU cache Still, you might read a stale value, since on modern architectures you have multiple cores with individual cache that is not kept in sync automatically. You need a read memory barrier, usually a platform-specific instruction. On Wintel, thread synchronization functions will automatically add a full memory barrier, or you can use the InterlockedXxxx functions. MSDN: Memory and Synchronization issues, MemoryBarrier Macro [edit] please also see drhirsch's comments.
1,351,129
1,351,650
Calculating 3D tangent space
In order to use normal mapping in GLSL shaders, you need to know the normal, tangent and bitangent vectors of each vertex. RenderMonkey makes this easy by providing it's own predefined variables (rm_tangent and rm_binormal) for this. I am trying to add this functionality to my own 3d engine. Apparently it is possible to calculate the tangent and bi tangent of each vertex in a triangle using each vertex's xyz coordinates, uv texture coordinates and normal vector. After some searching I devised this function to calculate the tangent and bitangent for each vertex in my triangle structure. void CalculateTangentSpace(void) { float x1 = m_vertices[1]->m_pos->Get(0) - m_vertices[0]->m_pos->Get(0); float x2 = m_vertices[2]->m_pos->Get(0) - m_vertices[0]->m_pos->Get(0); float y1 = m_vertices[1]->m_pos->Get(1) - m_vertices[0]->m_pos->Get(1); float y2 = m_vertices[2]->m_pos->Get(1) - m_vertices[0]->m_pos->Get(1); float z1 = m_vertices[1]->m_pos->Get(2) - m_vertices[0]->m_pos->Get(2); float z2 = m_vertices[2]->m_pos->Get(2) - m_vertices[0]->m_pos->Get(2); float u1 = m_vertices[1]->m_texCoords->Get(0) - m_vertices[0]->m_texCoords->Get(0); float u2 = m_vertices[2]->m_texCoords->Get(0) - m_vertices[0]->m_texCoords->Get(0); float v1 = m_vertices[1]->m_texCoords->Get(1) - m_vertices[0]->m_texCoords->Get(1); float v2 = m_vertices[2]->m_texCoords->Get(1) - m_vertices[0]->m_texCoords->Get(1); float r = 1.0f/(u1 * v2 - u2 * v1); Vec3<float> udir((v2 * x1 - v1 * x2) * r, (v2 * y1 - v1 * y2) * r, (v2 * z1 - v1 * z2) * r); Vec3<float> vdir((u1 * x2 - u2 * x1) * r, (u1 * y2 - u2 * y1) * r, (u1 * z2 - u2 * z1) * r); Vec3<float> tangent[3]; Vec3<float> tempNormal; tempNormal = *m_vertices[0]->m_normal; tangent[0]=(udir-tempNormal*(Vec3Dot(tempNormal, udir))); m_vertices[0]->m_tangent=&(tangent[0].Normalize()); m_vertices[0]->m_bitangent=Vec3Cross(m_vertices[0]->m_normal, m_vertices[0]->m_tangent); tempNormal = *m_vertices[1]->m_normal; tangent[1]=(udir-tempNormal*(Vec3Dot(tempNormal, udir))); m_vertices[1]->m_tangent=&(tangent[1].Normalize()); m_vertices[1]->m_bitangent=Vec3Cross(m_vertices[1]->m_normal, m_vertices[1]->m_tangent); tempNormal = *m_vertices[2]->m_normal; tangent[2]=(udir-tempNormal*(Vec3Dot(tempNormal, udir))); m_vertices[2]->m_tangent=&(tangent[2].Normalize()); m_vertices[2]->m_bitangent=Vec3Cross(m_vertices[2]->m_normal, m_vertices[2]->m_tangent); } When I use this function and send the calculated values to my shader, the models look almost like they do in RenderMonkey but they flicker in a very strange way. I traced the problem to the tangent and bitangent I am sending OpenGL. This leads me to suspect that my code is doing something wrong. Can anyone see any problems or have any suggestions for other methods to try? I should also point out that the above code is very hacky and I have very little understanding of the math behind what is going on.
Found the solution. Much simpler (but still a little hacky) code: void CalculateTangentSpace(void) { float x1 = m_vertices[1]->m_pos->Get(0) - m_vertices[0]->m_pos->Get(0); float y1 = m_vertices[1]->m_pos->Get(1) - m_vertices[0]->m_pos->Get(1); float z1 = m_vertices[1]->m_pos->Get(2) - m_vertices[0]->m_pos->Get(2); float u1 = m_vertices[1]->m_texCoords->Get(0) - m_vertices[0]->m_texCoords->Get(0); Vec3<float> tangent(x1/u1, y1/u1, z1/u1); tangent = tangent.Normalize(); m_vertices[0]->m_tangent = new Vec3<float>(tangent); m_vertices[1]->m_tangent = new Vec3<float>(tangent); m_vertices[2]->m_tangent = new Vec3<float>(tangent); m_vertices[0]->m_bitangent=new Vec3<float>(Vec3Cross(m_vertices[0]->m_normal, m_vertices[0]->m_tangent)->Normalize()); m_vertices[1]->m_bitangent=new Vec3<float>(Vec3Cross(m_vertices[1]->m_normal, m_vertices[1]->m_tangent)->Normalize()); m_vertices[2]->m_bitangent=new Vec3<float>(Vec3Cross(m_vertices[2]->m_normal, m_vertices[2]->m_tangent)->Normalize()); }
1,351,199
1,351,390
How can I create a static object member of class?
I am fairly new to c++, especially in its techniques. My question is, how can I create a static object member of a class itself. What I mean is I declared a static member object inside a class. Example: CFoo:CFoo *pFoo[2] = {0}; class CFoo { public: static CFoo *pFoo[2]; public: CFoo(int a); public: CFoo *getFoo(); }; Now the problem is, how can I create the pFoo, like I want to create two static object pFoo, pFoo[0] = new CFoo(0); pFoo[1] = new CFoo(1); so that I can use the getFoo method to return one of the pFoo, like, CFoo *getFoo() { return pFoo[0]; //or pFoo(1); } Thanks alot guys. Hope my questions are clear. Thanks again in advance. -sasayins
Let's improve your code one step at a time. I'll explain what I'm doing at each step. Step 1, this isn't Java. You don't need to specify public for every member. Everything after public: is public until you specify something else (protected or private). I also moved the definition of pFoo after the class. You can't define a variable before it's been declared. class CFoo { public: static CFoo *pFoo[2]; CFoo(int a); CFoo *getFoo(); }; CFoo* CFoo::pFoo[2] = {0}; Step 2, pFoo probably shouldn't be public if you're going to have a getFoo member function. Let's enforce the interface to the class instead of exposing the internal data. class CFoo { public: CFoo(int a); CFoo *getFoo(); private: static CFoo *pFoo[2]; }; CFoo* CFoo::pFoo[2] = {0}; Step 3, you can return by pointer without bothering to use new. I've written C++ code for many years, and I'd have to look up how you delete the memory that was newed for a static member variable. It's not worth the hassle to figure it out, so let's just allocate them on the stack. Also, let's return them by const pointer to prevent users from accidentally modifying the two static CFoo objects. class CFoo { public: CFoo(int a); const CFoo *getFoo(); private: static CFoo foos[2]; }; CFoo CFoo::foos[2] = {CFoo(0), CFoo(1)}; The implementation of getFoo then becomes: const CFoo * CFoo::getFoo() { return &foos[0]; // or &foos[1] } IIRC, the static member foos will be allocated the first time you create a CFoo object. So, this code... CFoo bar; const CFoo *baz = bar.getFoo(); ...is safe. The pointer named baz will point to the static member foos[0].
1,351,217
1,351,422
QThread::wait() and QThread::finished()
Does QThread::wait() return (i.e., unblocks execution) after calling all the slots that were associated with QThread::finished() signal? Thanks in advance.
No, it may return before, during or after a slot associated with signal finished() is being executed. This depends on the type of signal-slot connection, read about queued connections and direct connections.
1,351,381
1,351,398
FFT Problem (Returns random results)
I've got this code, but it keeps returning random frequencies from 0 to about 1050. Please can you help me understand why this is happening. My data length is 1024, sample rate is 8192, and data is a short array filled with input data from the mic. float *iSignal = new float[2048]; float *oSignal = new float[2048]; int pitch = 0; for(x=0;x<=1024;x++) { iSignal[x] = data[x]; } fft(iSignal,oSignal,1024); //Input data, output data, length of input and output data for(int y=0;y< 2048;y+=2) { if((pow(oSignal[y],2)+pow(oSignal[y+1],2))>(pow(oSignal[pitch],2)+pow(oSignal[(pitch)+1],2))) { pitch = y; } } double pitchF = pitch / (8192.0/1024); printf("Pitch: %f\n",pitchF); Thanks, Niall. Edit: Changed the code, but it's still returning random frequencies.
Assuming oSignal is filled with complex numbers in such a way, that real and imaginary parts alternate, it might help to change for(int y=0;y< 8191;y++) to for(int y=0;y< 8191;y+=2) Edit: I didn't even notice that you're passing only 1024 samples. You must pass as many time-domain samples as there will be frequency-domain samples, in your case 4096. Edit: One more thing: you're obviously trying to find the base frequency of something. Unless that something is a computer generated tone or a human whistle (both of which are very pure tones), you might be disappointed by the result. The simple method you posted barely works for flute. Edit: For voice and guitar you're out of luck. I wrote a program some time ago that displays the frequency domain, try it out, you'll see the problem. There are also sources available, if you're interested. Final edit: You might want to read the Wikipedia article on pitch detection. Concentrate on time-domain approaches.
1,351,418
1,352,237
Adding VC++ to Eclipse toolchain
I want to write a program to link with binaries already created with VC++. What are the steps to add a toolchain for VC++ in Eclipse? Has anyone tried it successfully? If so, does the debugger still work?
There is a toolchain implementation for VC++. The build plugin is called org.eclipse.cdt.msw.build, and there is a set of debugger plugins called org.eclipse.cdt.msw.debug.*. I think the build integration works, but the debugger integration still needs some work before it is usable. Doug Schaefer on the CDT team has blogged about this several times, and has been running the Wascana project for some time to this end. Unfortunately, he's no longer working actively on Wascana. If you wanted to put in some effort in bringing the VC++ toolchain and debug support closer to working condition, it would be very appreciated. I know that there are many people who would like to have that (myself included). (The cdt-dev list can surely help you with further help and pointers.)
1,352,095
1,352,111
typechecking provided on enum
I would expect the following code snippet to complain about trying to assign something other that 0,1,2 to a Color variable. But the following does compile and I get the output Printing:3 3 Can anybody explain why? Is enum not meant to be a true user-defined type? Thanks. enum Color { blue=0,green=1,yellow=2}; void print_color(Color x); int main(){ Color x=Color(3); print_color(x); std::cout << x << std::endl; return 0; } void print_color(Color x) { std::cout << "Printing:" << x << std::endl; }
Since you manually cast the 3 to Color, the compiler will allow you to do that. If you tried to initialize the variable x with a plain 3 without a cast, you would get a diagnostic. Note that the range of values an enumeration can store is not limited by the enumerators it contains. It's the range of values of the smallest bitfield that can store all enumerator values of the enumeration. That is, the range of your enumeration type is 0..3: 00 01 10 11 The value 3 is thus still in range, and so the code is valid. Had you cast a 4, then the resulting value would be left unspecified by the C++ Standard. In practice, the implementation has to chose an underlying integer type for the enumeration. The smallest type it can choose is char, but which is still able to at least store values ranging up to 127. But as mentioned, the compiler is not required to convert a 4 to a value of 4, because it's outside the range of your enumeration. I figure i should post some explanation on the difference of "underlying type" and "range of enumeration values". The range of values for any type is the smallest and largest value of that type. The underlying type of an enumeration must be able to store the value of any enumerator (of course) - and two enumerations that have the same underlying type are layout compatible (this allows some flexibility in case a type mismatch occurs). So while the underlying type is meant to fix the object representation (alignment and size), the values of the enumeration is defined as follows in 7.2/6 For an enumeration where emin is the smallest enumerator and emax is the largest, the values of the enumeration are the values of the underlying type in the range bmin to bmax, where bmin and bmax are, respectively, the smallest and largest values of the smallest bit-field that can store emin and emax . It is possible to define an enumeration that has values not defined by any of its enumerators. [Footnote: On a two’s-complement machine, bmax is the smallest value greater than or equal to max (abs(emin) − 1 ,abs(emax)) of the form 2M−1; bmin is zero if emin is non-negative and −(bmin+1) otherwise.]
1,352,334
1,352,684
QCalendarWidget as "Pop-up", not as new Window?
I want to create a Settings-Widget, where I can choose a Date. Because it isn't nice to create 3 QLineEdits to call the QDate-Constructor with QDate(int year, int month, int day), I thought it would be better, if you can push a "show calendar"-Button for example, where you can choose the date. But I don't want to show this calendar in a new Window, I want to show it as a "Pop-up" (I don't know how to explain this), which you might know for example from the OpenOffice-Settings. You have any idea how to implement that?
For an alternate option, have you considered using QDateEdit? It will allow your users to edit the date in a format that is consistent with the rest of the operating system.
1,352,370
1,352,376
C Static Array Initialization - how verbose do I need to be?
To initialize an int array with all zeros, do I need to use: int foo[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Or, will this work: int foo[10] = {0};
int foo[10] = {0}; This is very fine :) Note that if you do the following: int foo[10] = {1}; Only the first element of the array will be initialized with the non-zero number whereas the rest will be initialized with zeros.
1,352,483
1,353,001
Protect private key in Qt application
I have a Qt application written in C++ that uses a SSL-connection (QSslSocket) with another application for extra security. However, the application has a private key embedded in it. With applications like Process Explorer it's really easy to fish out the private key. (Properties of file -> Strings) Security is not very important for my application but it would be nice to make a little bit more difficult getting the private key from my application. Is there any way?
You may need of solutions to your problem from a different angle. I agree with Shoosh's answer in that no matter what you do a person with the right tools and knowledge will be able to break your code and figure out your private key. What you need to do is either externalize the data or mitigate the risks if your private keys are found. The best way to externalize any private data is to encrypt it with a user supplied password that must be entered by the user to be used. Unfortunately this is not really reasonable for most applications. To mitigate the risks I normally try to ensure that only the one 'install' is compromised if the security is broken. For example, randomly generate the private key data on install. For client/server applications you could follow the https model and use public/private key communication to exchange a randomly generated encryption key. If each client install has there own public/private key set, then the server can tell what clients are connecting and also if there is a problem they can outlaw clients. Hope that helps.
1,352,571
1,352,630
What's the difference between C++0x concepts and The Boost Concept Check Library (BCCL)?
Concepts didn't make the C++0x standard, but Boost still provides The Boost Concept Check Library (BCCL). I guess that BCCL doesn't cover everything that was meant to into the C++0x standard. What is the difference between BCCL and the proposed C++0x solution?
Checking the template definition A big difference of concepts to these manual solutions is that concepts allow the definition of a template to be type-checked without doing anything special. The concept check library allows only the *use* of it to be type checked (unless you manually write test-instantiation types or make use of provided types for standard cases, see below). Example: template<typename InputIterator> int distance(InputIterator a, InputIterator b) { return b - a; } You may now sprinkle that template with concept checks and traits, but you will never get an error after writing that template - because the Standard allows the compiler to delay compiling the template until instantiation. For checking, you have to write "archetype" classes, which contain exactly those operations that are required by the interface and then instantiate them artificially. Reading the documentation of BCCL, i found it already includes the common archetypes like "default constructible". But if you write your own concepts, you will have to also provide your own archetypes, which isn't easy (you have to find exactly the minimal functionality a type has to provide). For example, if your archetype contains a operator-, then the test of your template with that (incorrect) archetype will succeed, although the concepts don't require such an operator. The rejected concepts proposal creates archetypes for you automatically, based on the requirements that were specified and that were implied (a pointer type T* used in a parameter will imply the PointeeType requirement for T, for example). You don't have to care about this stuff - except of course when your template definition contains a type error. Checking semantic requirements Consider this code, using hypothetical concept checks template<ForwardIterator I> void f(I a, I b) { // loop two times! loopOverAToB(a, b); loopOverAToB(a, b); } The BCCL manual says that semantic requirements are not checked. Only syntax requirement and types are checked. Consider a forward iterator: There exists the semantic requirement that you may use it in multi-pass algorithms. Syntax-checking only won't be able to test this requirement (think about what happens if a stream iterator accidentally would pass that check!) In the rejected proposal, you had to explicitly put auto in front of concept definitions to make the compiler flag success after syntax-checking. If auto wasn't specified, then a type explicitly had to define a concept map to say it supports that concept. A stream iterator would thus never be taken to pass a ForwardIterator check. Syntax remapping This was another feature. A template such as template<InputIterator I> requires OutputStreamable<I::value_type> void f(I a, I b) { while(a != b) std::cout << *a++ << " "; } Can be used like the following, if the user would provide a concept map that teaches the compiler how to dereference an integer, and thus how an integer satisfies the InputIterator concept. f(1, 10); This is the benefit of a language-based solution, and cannot be solved by BCCL ever, i believe. Concept based Overloading On a quick read of BCCL, i can also not spot anything that allows this to happen. A concept matching failure seems to cause a hard compilation error. The rejected proposal allows the following: template<ForwardIterator I> I::difference_type distance(I a, I b) { I::difference_type d = 0; while(a != b) ++a, ++d; return d; } template<RandomAccessIterator I> I::difference_type distance(I a, I b) { return b - a; } If a type could be used with both templates, then the second template would be used, because it's more specialized: RandomAccessIterator refines the ForwardIterator concept.
1,352,732
1,352,824
What do these C++ code snippets do?
#ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif Why define these tags? CSortHeaderCtrl::CSortHeaderCtrl() : m_iSortColumn( -1 ) , m_bSortAscending( TRUE ) { } What are the two functions after colon used for? BEGIN_MESSAGE_MAP(CSortHeaderCtrl, CHeaderCtrl) //{{AFX_MSG_MAP(CSortHeaderCtrl) // NOTE - the ClassWizard will add and remove mapping macros here. //}}AFX_MSG_MAP END_MESSAGE_MAP() Are there any similar things in C# like this? What's this used for? virtual ~CSortHeaderCtrl(); Why set the destructor function to be virtual? void CSortHeaderCtrl::Serialize( CArchive& ar ) When will this function be called? Is this extended from parent? By the way, when you want to extend a MFC class, what document you will read? Since we don't know what function it has, what function can we override? The following is the header file: /* File: SortHeaderCtrl.h Purpose: Provides the header control, with drawing of the arrows, for the list control. */ #ifndef SORTHEADERCTRL_H #define SORTHEADERCTRL_H #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CSortHeaderCtrl : public CHeaderCtrl { // Construction public: CSortHeaderCtrl(); // Attributes public: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CSortHeaderCtrl) public: virtual void Serialize(CArchive& ar); //}}AFX_VIRTUAL // Implementation public: virtual ~CSortHeaderCtrl(); void SetSortArrow( const int iColumn, const BOOL bAscending ); // Generated message map functions protected: void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct ); int m_iSortColumn; BOOL m_bSortAscending; //{{AFX_MSG(CSortHeaderCtrl) // NOTE - the ClassWizard will add and remove member functions here. //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // SORTHEADERCTRL_H
Why define these tags ? See jcopenha's answer. What is the two functions after colon used for ? See Peter's answer. Is there any similar things in C# like this ? What's this used for ? In C# it might be implemented as a dictionary of delegates. It's called a "message map" (probably described in one of the subsections of MFC Library Reference Message Handling and Mapping). Its contents are typically created/edited via the IDE "Class Wizard" (not edited manually using the code/text editor). Why set the destructor function to be virtual ? In C++, if a class might be subclassed then its destructor should almost always be virtual (because otherwise if it's not virtual and you invoke it by deleting a pointer to the superclass, the destructor of the subclass wouldn't be invoked). When will this function be called ? That's probably described here: MFC Library Reference Serialization in MFC. is this extended from parent? Acording to that link I just gave above, it's the CObject ancestor class: "MFC supplies built-in support for serialization in the class CObject. Thus, all classes derived from CObject can take advantage of CObject's serialization protocol." By the way, when you want to extend a MFC class, what document you will read? The MFC reference documentation. Since we don't know what function it have, what function we can override... You can typically override everything that virtual and not private. I think you can also/instead use the Class Wizard that's built-in to the IDE. CSortHeaderCtrl is apparently a 3rd-party class, though, not a Microsoft class. Perhaps it's authors/vendor wrote some documentation for it, if you're supposed to be using it.
1,352,784
1,352,791
Preprocessor examples in C language
I want some examples of C preprocessor directives, such as: #define pi 3.14 #define MAX 100 I know only this. I want to know more than this, more about preprocessor directives.
The biggest example would be #include<stdio.h> But there are a fair amount. You can also define macros: #define MAX(X,Y) (((X) > (Y)) ? (X) : (Y)) And use header guards #ifndef A_H #define A_H // code #endif There are proprietary extensions that compilers define to let you give processing directives: #ifdef WIN32 // WIN32 is defined by all Windows 32 compilers, but not by others. #include <windows.h> #else #include <unistd.h> #endif And the if statement cause also be used for commenting: #if 0 int notrealcode = 0; #endif I often use the preprocessor to make debug builds: #ifdef EBUG printf("Debug Info"); #endif $ gcc -DEBUG file.c //debug build $ gcc file.c //normal build And as everyone else has pointed out there are a lot of places to get more information: http://predef.sourceforge.net/ http://en.wikipedia.org/wiki/C_preprocessor http://gcc.gnu.org/onlinedocs/cpp/
1,352,875
1,353,512
Naming convention for a variable that works like a constant
I have a variable that I'm using like a constant (it will never change). I can't declare it as a constant because the value gets added at runtime. Would you capitalize the variable name to help yourself understand that data's meaning? Or would you not because this defies convention and make things more confusing? The larger question: Do you follow conventions even if the scenario isn't typical of the convention, but close enough that it might help you, personally, to understand things?
Encapsulate it. #include <iostream> class ParamFoo { public: static void initializeAtStartup(double x); static double getFoo(); private: static double foo_; }; double ParamFoo::foo_; void ParamFoo::initializeAtStartup(double x) { foo_ = x; } double ParamFoo::getFoo() { return foo_; } int main(void) { ParamFoo::initializeAtStartup(0.4); std::cout << ParamFoo::getFoo() << std::endl; } This should make it pretty clear that you shouldn't be setting this value anywhere else but at the startup of the application. If you want added protection, you can add some private guard boolean variable to throw an exception if initializeAtStartup is called more than once.
1,352,959
1,352,969
Using COM object from C++ that in C#.NET returns object []
I have a COM object that I'm trying to use from C++ (not .NET), and all of the example programs and manual are written assuming the use of C#.NET or VB.NET. COM is new to me so I'm a bit overwhelmed. I'm using #import on the TLB but am struggling to deal with the variants that are used as parameters. I have one particular method, that according to the docs and the example programs in C#.NET, is supposed to return an object[]. Then I'm supposed to cast the first entry in this array to a ControlEvent which then tells me what to do with the rest of the objects in the array. The C#.NET example looks like: object [] objEvent = (object []) Ctl.GetEvent(); ControlEvent ev = (ControlEvent) objEvent[0]; In my case, GetEvent is returning me a _variant_t and I need to know how to convert this to an object[] so that I can further process. Its not clear to me even how I express 'object' in C++. I see _variant_t documentation showing me a million things I can convert the variant to, but none of them seem to be converting to anything I can use. I'm hoping for some assistance converting the above C#.NET code to Visual C++ Thanks.
Typically, you look at the vt member of the variant to see what type of thing it actually is. In this case I would expect it to be an array, so you would expect that the vartype would be some variation on VT_ARRAY (usually it is bitwise OR'ed with the type of the members). Then, you get the parray member which contains the SAFEARRAY instance that actually holds the array, and use the normal safe array functions to get the data out of the array.
1,353,118
1,353,140
How to set sockets to blocking mode in Windows?
I'm doing some fairly simple cross-platform TCP socket programming. I have unfortunately found out that when compiled on Windows, my sockets are non-blocking by default, while on OS X they are blocking by default. How do I force a socket into blocking mode on Windows? Do they normally default to non-blocking mode or is something terribly wrong? My code is based in part on these simple examples: http://cs.baylor.edu/~donahoo/practical/CSockets/code/TCPEchoClient.c http://cs.baylor.edu/~donahoo/practical/CSockets/code/TCPEchoServer.c
I believe this reference may help; note, in particular, that Although blocking operations on sockets are supported under Windows Sockets, their use is strongly discouraged. Programmers who are constrained to use blocking mode -- for example, as part of an existing application which is to be ported -- should be aware of the semantics of blocking operations in Windows Sockets. If you're fully aware of the zillion issues listed here, and find dealing with all of them preferable to designing your program to fit in well with Windows rather than being a half-beeped port from Unix, go right ahead with a ioctlsocket call with the cmd argument set to FIONBIO and the third argument pointing to a longword worth 0. But, don't say you weren't warned;-).
1,353,144
1,354,058
Subclassing a window with a functor (Win32)
Quick sanity check: Is it possible to subclass a window using a functor? I'm running into a situation where I want to have some data available in the win proc, but GWLP_USERDATA is already being used. A functor seems like a good alternative, but I'm having trouble getting it to work. Here's the basics: class MyWinProc { // Win Proc Functor public: MyWinProc(ExternalClass* obj, HWND window) : obj(obj), window(window) { oldWinProc = SubclassWindow(window, this); // Apply Subclass } virtual ~MyWinProc() { SubclassWindow(window, oldWinProc); // Remove Subclass } LRESULT CALLBACK operator()(HWND, UINT, WPARAM, LPARAM) { switch( uMsg ) { case WM_MOUSEMOVE: { obj->onMouseMove(/*etc*/); break; } } return CallWindowProc(oldWinProc, hWnd, uMsg, wParam, lParam); } private: ExternalClass* obj; HWND window; WNDPROC oldWinProc; }; Seems all well and good, but when I hit DispatchMessage() in me message pump, I "Access Violation Writing Location 0x00000000", obviously not a good sign. Remove the call to the above code and life is happy again. :( So is this even possible, or am I going about it entirely the wrong way?
GWLP_USERDATA is not the only way to store data associated with a window, you can also use SetProp(). And at least on x86, you can do ATL style thunking (A small piece of asm code that puts your class pointer in ecx and then jumps to your wndproc) You can find some links about that in a answer I posted here
1,353,161
1,353,442
What's the easiest way to call Postgres from a MinGW program?
All I need is get MinGW talking to Postgres. I've considered several options: Use libpq. The libpq.lib that comes with Postgres for Windows links okay, but crashes when I use the library. I think because it was compiled for VC++. I can't find just the libpq code, so I'd have to recompile the entire Postgres tree in MinGW. Not easy. Use libpqxx. Requires libpq! Use libodbcxx. Requires some sort of ODBC manager like iodbc. Maybe I can use iodbc directly. Since this is just Windows for now can I use -lodbc on my linker and use some Windows specific commands? Option 1 sounds the least painful. I'm pretty sure the project will use Postgres, not too sure if the project will stay on Windows. Is there a simple way to get this functionality?
You can rebuild just libpq if you have to. Run "./configure" and then run "make" in just src/interfaces/libpq. But really, the msvc built libpq should work just fine with mingw. It's just a standard Windows DLL. It may be an issue with the .lib - but the DLL should be fine. AFAIK, only the PQtrace() functionality will be broken - because of the way MSVCRT works, that only works if you have the exact same version of the runtime. You should also be able to generate an import library directly off the DLL, if the .LIB doesn't work. Or does MingW even allow you to link directly to the DLL - see their wiki Getting libpq to work is likely a lot easier than odbc.
1,353,263
1,353,284
How to unblock ConnectNamedPipe and ReadFile? [C#]
I have a class (NamedPipeManager) which has a thread (PipeThread) that waits for a NamedPipe connection using (ConnectNamedPipe) and then reads (ReadFile) - these are blocking calls (not-overlapped) - however there comes a point when I want to unblock them - for example when the calling class tries to stop the NamedPipeManager... How can I interupt it? Using Thread.abort? Thread.interrupt? Is there a proper way to handle this? Refer to the code below which illustrates my current situation main() { NamedPipeManager np = new NamedPipeManager(); ... do stuff ... ... do stuff ... np.Stop(); // at this point I want to stop waiting on a connection } class NamedPipeManager { private Thread PipeThread; public NamedPipeManager { PipeThread = new Thread(new ThreadStart(ManagePipes)); PipeThread.IsBackground = true; PipeThread.Name = "NamedPipe Manager"; PipeThread.Start(); } private void ManagePipes() { handle = CreateNamedPipe(..., PIPE_WAIT, ...); ConnectNamedPipe(handle, null); // this is the BLOCKING call waiting for client connection ReadFile(....); // this is the BLOCKING call to readfile after a connection has been established } public void Stop() { /// This is where I need to do my magic /// But somehow I need to stop PipeThread PipeThread.abort(); //?? my gut tells me this is bad } }; So, in function Stop() - how would I gracefully unblock the call to ConnectNamedPipe(...) or ReadFile(...)? Any help would be appreciated. Thanks,
Starting with Windows Vista, there is a CancelSynchronousIO operation available for threads. I don't think there is a C# wrapper for it, so you would need to use PInvoke to call it. Before Vista, there isn't really a way to perform such an operation gracefully. I would advise against using thread cancellation (which might work, but doesn't qualify as graceful). Your best approach is to use overlapped IO.
1,353,384
1,353,397
"l-value required" error
When do we get "l-value required" error...while compiling C++ program???(i am using VC++ )
An "lvalue" is a value that can be the target of an assignment. The "l" stands for "left", as in the left hand side of the equals sign. An rvalue is the right hand value and produces a value, and cannot be assigned to directly. If you are getting "lvalue required" you have an expression that produces an rvalue when an lvalue is required. For example, a constant is an rvalue but not an lvalue. So: 1 = 2; // Not well formed, assigning to an rvalue int i; (i + 1) = 2; // Not well formed, assigning to an rvalue. doesn't work, but: int i; i = 2; Does. Note that you can return an lvalue from a function; for example, you can return a reference to an object that provides a operator=(). As pointed out by Pavel Minaev in comments, this is not a formal definition of lvalues and rvalues in the language, but attempts to give a description to someone confused about an error about using an rvalue where an lvalue is required. C++ is a language with many details; if you want to get formal you should consult a formal reference.
1,353,421
1,353,425
The right way to create pointer to pointer object?
What is the right way to create a pointer to pointer object? Like for example, int **foo; foo = new int[4][4]; Then the compiler gives me an error saying "cannot convert from int (*)[4] to int **. Thanks.
int **foo = new int*[4]; for (int i = 0; i < 4; i++) foo[i] = new int[4]; Clarification: In many languages the code above is called a jagged array and it's only useful when the "rows" have different sizes. C++ has no direct language support for dynamically allocated rectangular arrays, but it's easy to write it yourself: int *foo = new int[width * height]; foo[y * height + x] = value;
1,353,757
1,353,816
How do I refer to std::sin(const valarray<double> &)?
I'm having trouble with some valarray function pointer code: double (*fp)(double) = sin; valarray<double> (*fp)(const valarray<double> &) = sin; The first compiles, the second gives: error: no matches converting function 'sin' to type 'class std::valarray<double> (*)(const class std::valarray<double>&)'
This compiles, using the __typeof__ GCC extension. Looks like GCC's valarray uses expression templates to delay calculation of the sinus. But that will make the return type of the sin template not exactly valarray<T>, but rather some weird complex type. #include <valarray> template<typename T> struct id { typedef T type; }; int main() { using std::valarray; using std::sin; id<__typeof__(sin(valarray<double>()))>::type (*fp)(const valarray<double> &) = sin; } Edit: See AProgrammer's standard quote for why GCC is fine doing that. Edit: Standard compliant workaround Doing this without __typeof__ in a strictly Standard conforming way is a bit tricky. You will need to get the return type of sin. You can use the conditional operator for this, as Eric Niebler has shown. It works by having the sin function not actually called, but only type-checked. By trying to convert the other branch (the one which is actually evaluated) of the conditional operator to that same type, we can generate a dummy parameter just to be able to deduce the type of the function pointer: #include <valarray> using std::valarray; template<typename T> struct id { typedef T type; }; struct ded_ty { template<typename T> operator id<T>() { return id<T>(); } }; template<typename E, typename T> id<T(*)(valarray<E> const&)> genFTy(T t) { return id<T(*)(valarray<E> const&)>(); } template<typename T> void work(T fp, id<T>) { // T is the function pointer type, fp points // to the math function. } int main() { work(std::sin, 1 ? ded_ty() : genFTy<double>(std::sin(valarray<double>()))); } If you want to get the address right away, you can write work so it returns fp again. template<typename T> T addy(T fp, id<T>) { return fp; } Now, you can finally write a macro to encapsulate the conditional operator trickery, and use it when you want to get the address of any such math function. #define DEDUCE(FN,Y) (1 ? ded_ty() : genFTy<Y>(FN(std::valarray<Y>()))) To get the address and pass it to some generic function, the following works then std::transform(v1.begin(), v1.end(), v1.begin(), addy(std::sin, DEDUCE(std::sin, double))); std::transform(v2.begin(), v2.end(), v2.begin(), addy(std::cos, DEDUCE(std::cos, double)));
1,353,769
1,353,906
Haxe - Generating Exe's (cpp)
I've been instructed to download and install FlashDevelop and it seems fine but I don't know how to generate exe files when writing programs in Haxe. I try to Build or Run the project in FlashDevelop BUT it just doesn't do anything. Can anybody please advise me on how to do this? Thank you
The CPP target is the youngest in the Haxe world and so still a little rough on the edges; add in more complexity because it depends on external tools to properly work. Made that premise, try to create a new Haxe/CPP project in FlashDevelop, open the Main class and add a simple trace("hello world!"); line. Hit F5 to start the "compile and run" process. You'll see in the status bar the message "Build started ..." and you can follow the process looking at the "Output Panel". If your environment is set correctly it will compile the whole project and open a DOS window where it will execute the generated executable (you can find it in the bin folder). If you receive an error then your environment is not yet ready to build CPP applications with Haxe. To fix that follow the setup instructions you can find here. An easy alternative to produce native execubles (yes, you can compile the same for Win/Mac/Linux) you can target neko to produce a .n file and nekotools to transform it in the exe form. Just type: nekotools boot main.n
1,353,973
1,353,981
C++ template, linking error
I have a problem in calling a template class I have. I declared a new type name Array, which is a template; In the .hpp file: template <typename T> class Array { public: Array(); }; In the .cpp file: template <typename T> Array<T>::Array() { //Do something } In main: Array<int> arr; I get Linkage error: unresolved external symbol to the ctor. Any Idea?
Template functions, including member functions, must be written entirely in the header files. This means that if you have a template class, its implementation must be entirely in a header file. This is because the compiler needs to have access to the entire template definition (not just the signature) in order to generate code for each instantiation of the template.
1,354,026
1,354,104
CEvent-like behaviour with Boost.Thread
Problem in words: For my application, I have a class that reads from a serial port. It uses Windows primitives for COM port handling and had a thread for asynchronous reading. I'm trying to convert this away from Windows primitives using Boost libraries such as Boost.Asio and Boost.Thread. In the Windows port, my IO thread had several MFC CEvent variables, each of which represented a message: Read requested, Write requested, Read completed, Write completed, IO Cancelled. These were waited on with WaitForMultipleObjects. The problem I have is that Boost.Thread seems to have analogues for neither CEvent nor WaitForMultipleObjects. The closest I have come is by discarding these and replacing the events with a set of booleans, and then using a condition_variable, which has its notify_all() function called whenever a boolean changes. However, boost::condition_variable differs in one critical way from CEvent: if a CEvent is signalled while it is not being waited on, then the next wait on it immediately succeeds. With boost::condition_variable, any notify function is ignored if it is not waiting. This means that there is always a gap between checking for the flags and waiting for the condition_variable in which a notification can be lost. This causes the thread to hang. Does anybody know of a solution to this problem? Problem in code: // Old IO Thread CEvent msg_cancel; CEvent msg_read_req; CEvent msg_write_req; CEvent msg_read_comp; CEvent msg_write_comp; CEvent events[] = { msg_cancel, msg_read_req, msg_write_req, msg_read_comp, msg_write_comp }; bool cancel = false; while (!cancel) { switch(WaitForMultipleObjects(5, events, false, INFINITE)) { case WAIT_OBJECT_0 : // msg_cancel cancel = true; break; ... } } How to emulate that in Boost.Thread?
As you said, to resemble a windows style event you need a condition-variable plus a boolean flag. Of course you can combine several boolean flags into one if it satisfies your needs. However, the problem you mentioned (condition variables never get an active state where wait will immediately return) is usually solved that way: condition-variable mutex main-thread: lock(mutex) { start condition-signaling-thread } while(some predicate) { condition-variable.wait(mutex) do-stuff } condition-signaling-thread: loop: lock(mutex) { do-whatever } condition-variable.notify(); By having the second thread to wait until the mutex is unlocked by the thread which will handle the condition you can ensure that each condition is handled. (Note: In Java the notify() method has to be called within the lock, which, depending on implementation details, could result in worse performance if done in C++, but ensures that the programmer has at least once thought about how to synchronize the firing of the condition with the receiver). The reason why boost.thread does not provide windows-style events (and posix-semaphores, btw) is that those primitives make it quite easy to screw up. If you do not plan to port your application to another platform, adapting your application to this different style may not be worth it.
1,354,124
1,370,611
C++ ctype facet for UTF-8 in mingw
In a project all internal strings are kept in utf-8 encoding. The project is ported to Linux and Windows. There is a need for a to_lower functionality now. On POSIX OS I could use std::ctype_byname("ru_RU.UTF-8"). But with g++ (Debian 4.3.4-1), ctype::tolower() don't recognize Russian UTF-8 characters (latin text is lowercased fine). On Windows, mingw's standard library throws exception "std::runtime_error: locale::facet::_S_create_c_locale name not valid" when I try to construct std::ctype_byname with "ru_RU.UTF-8" argument. How do I implement/find std::ctype for utf-8 on Windows? The project already depends on libiconv (codecvt facet is based on it), but I don't see an obvious way to implement to_lower with it.
If all you need is to_lower for Cyrillic characters you can write a function by yourself. АБВГДЕЖ in UTF8 D0 90 D0 91 D0 92 D0 93 D0 94 D0 95 D0 96 0A абвгдеж in UTF8 D0 B0 D0 B1 D0 B2 D0 B3 D0 B4 D0 B5 D0 B6 0A But don't forget that UTF8 is multibyte encoding. Also you can try to convert a string from UTF8 to wchar_t (using libiconv) and use Windows specific function to implement to_lower.
1,354,224
1,354,233
Multimap output after copying from map
This program stores pairs in a map, counting the number of times a word occurs. The goal is to have the data sorted by number of occurences and output in value/string form. Obviously the normal map sorts by the string key, so I had to reverse it. To do this I read in words, and increment their values appropriately in a map. Then I create a multimap and copy the pairs from the map into the multimap, but reversed. Then I iterate through the multimap, outputting the pairs. However, a runtime error occurs when I try to output the pairs and I'm not sure why. Here is the code: #include <map> #include <string> #include <iostream> using namespace std; int main() { map<string, int> words; multimap<int, string> words2; string s; while (true) { cin >> s; if (s == "0") break; ++words[s]; } map<string, int>::iterator p; for (p = words.begin(); p!=words.end(); ++p) words2.insert(make_pair(p->second, p->first)); multimap<int, string>::iterator p2; for (p2 = words2.begin(); p2!=words2.end(); ++p2) cout << p->first << ": " << p->second << '\n'; } Any help is appreciated. P.S. I read in different places that multimap can have multiple occurences of a key (which is why I used it in the first place) and/or multiple values in a single key. Some clarification would be nice regarding which is true or whether both are true. Also is there any type of copy algorithm for maps? I decided to just use a for loop for simplicity's sake, and it would probably be fairly easy to write a custom copy, but I'm just wondering (for copying maps to other pair containers and copying to output.)
for (p2 = words2.begin(); p2!=words2.end(); ++p2) cout << p->first << ": " << p->second << '\n'; Shouldn't the p's in your output statement be p2's ?
1,354,360
1,354,400
FRAPS alternative: Where to look and what for?
later this year I'm going to have a lot of time on my hands, and I thought I'd start a "small" project for myself and release it as open source. I'd like to code my own Fraps alternative. (or continue with Taksi http://taksi.sourceforge.net ). Fraps is a video & sound recording programm, which captures the screen during gameplay. It has way more functions than I need and its commercial. All I want is being able to record the screen / game I'm currently playing continuously including sound no other extras. Now this is a new area for me, but not the programming languages. I thought I'll be using C++ (& others if needed). What I need are hints where to look, and what to look for, where to read stuff rearding it. Etc. etc. I hope y'all can help me!
Here is some good info on the techniques used by FRAPS. http://www.woodmann.com/forum/archive/index.php/t-11023.htm
1,354,522
1,354,534
Simple C++ Error: "... undeclared (first use this function)"
I am working on my first C++ program for school. For some reason I am getting the following error when I try to compile it: `truncate' undeclared (first use this function) Full Source: #include <iostream> #include <math.h> using namespace std; #define CENTIMETERS_IN_INCH 2.54 #define POUNDS_IN_KILOGRAM 2.2 int main() { double feet, inches, centimeters, weight_in_kg, weight_in_lbs; // get height in feet and inches cout << "Enter height (feet): "; cin >> feet; cout << "Enter (inches): "; cin >> inches; // convert feet and inches into centimeters centimeters = ((12 * feet) + inches) * CENTIMETERS_IN_INCH; // round 2 decimal places and truncate centimeters = truncate(centimeters); printf("Someone that is %g' %g\" would be %g cm tall", feet, inches, centimeters); // weights for bmi of 18.5 weight_in_kg = truncate(18.5 * centimeters); weight_in_lbs = round(weight_in_kg * POUNDS_IN_KILOGRAM); printf("18.5 BMI would correspond to about %g kg or %g lbs", weight_in_kg, weight_in_lbs); // weights for bmi of 25 weight_in_kg = truncate(25 * centimeters); weight_in_lbs = round(weight_in_kg * POUNDS_IN_KILOGRAM); printf("25.0 BMI would correspond to about %g kg or %g lbs", weight_in_kg, weight_in_lbs); // pause output cin >> feet; return 0; } // round result double round(double d) { return floor(d + 0.5); } // round and truncate to 1 decimal place double truncate(double d) { return round(double * 10) / 10; } Any help would be appreciated. Thanks.
You need forward declaration before your main: double truncate(double d); double round(double d); You could just define your functions before main, that will solve the problem too: #include <iostream> #include <math.h> using namespace std; #define CENTIMETERS_IN_INCH 2.54 #define POUNDS_IN_KILOGRAM 2.2 // round result double round(double d) { return floor(d + 0.5); } // round and truncate to 1 decimal place double truncate(double d) { return round(double * 10) / 10; } int main() { ... }
1,354,621
1,354,668
Error: MFC projects cannot define _ATL_NO_EXCEPTIONS
I'm extending an open source project. After including afxcoll.h in a new C++ file in order to use CStringArray, I get this error: Error: MFC projects cannot define _ATL_NO_EXCEPTIONS I suspect I'll be able to fix the error by adding #defines or changing or rearranging the inclusion of headers, or, if that's not possible, using something other than CStringArray. What are your suggestions? Please ask questions in the comments for this question, not in your answer.
You could use CAtlArray<CString> instead of CStringArray, as this is compatible with _ATL_NO_EXCEPTIONS. The ATL collection classes are documented here. I normally prefer to use C++ standard library classes such as std::vector instead of the MFC container classes, though. I'd suggest investigating why _ATL_NO_EXCEPTIONS is defined in this project and whether it can be removed.
1,354,877
1,355,057
Qt -- pass events to multiple objects?
I basically have 3 layers (Window > Scene > View) that each need to handle a mouseMove event without blocking the others. It seems only the youngest child is getting the event though. I was hoping I could process the event and then call event->ignore() to pass the event back up the stack, but it doesn't seem to be working. Some relevant code if you need it: void EditorWindow::createScene() { m_scene = new EditorScene(this); m_view = new EditorView(m_scene); // ... } void EditorScene::mouseMoveEvent(QGraphicsSceneMouseEvent* mouseEvent) { printf("B\n"); // ... } void EditorView::mouseMoveEvent(QMouseEvent* event) { printf("C\n"); event->ignore(); } Only "C" is being printed. Note that EditorScene and EditorView receive different types of mouse events so it's not completely trivial to pass them around. The EditorWindow also needs the mouse coordinates; currently I'm sending a signal from one of the children which is caught by the window... but it shouldn't really be necessary to relay it that way, should it? Found this nice article. Calling ignore() tells Qt to find another receiver. Sounds like it should work, but perhaps it means an unrelated receiver. The proper way to propagate it is actually to call BaseClass::Event like so: void EditorView::mouseMoveEvent(QMouseEvent* event) { QGraphicsView::mouseMoveEvent(event); // propogate to parent widget printf("C\n"); } Now it's printing BCBCBC... which is great, but I can't seem to nudge it up one more level... Another edit: It was being propogated up properly, I just didn't have setMouseTracking enabled.
QGraphicsView::mouseMoveEvent(event); Doesn't propagate up to the parent -- it actually propagates down to the scene. Here is what's happens -- QGraphicsView receives QMouseEvent, translates it into QGraphicsSceneMouseEvent and passes it to the scene. Scene then passes it to appropriate item or, in your case, prints "B". Event handler then returns back to EditorView and prints "C". Then, if you explicitly ignore event (mouse move is accepted by default), Qt event handler will pass the event to parent of EditorView. So try ignoring after you print "C". Another thing about mouse move is this: If mouse tracking is switched off, mouse move events only occur if a mouse button is pressed while the mouse is being moved. If mouse tracking is switched on, mouse move events occur even if no mouse button is pressed. So make sure you have tracking enabled on parent of EditorView (or that you press buttons :)). EDIT: BTW, EditorScene is not a parent of EditorView. Well, it is in your code, but only in QObject meaning of parentship (memory management only). QGraphicsScene and View don't have normal family relationship -- scene can have multiple views and those views are children of unrelated parents. For window event propagation purposes you must have QWidget based parent. In fact, I'm pretty sure you reparent EditorView to EditorWindow, or one of its children (when you add it into layout). INSTAEDIT: For coordinates you want View itself to emit a signal. Both for decoupling reasons and because you probably want to show local coordinates of the view, and not of the parent window and not screen coordinates (right?). If you actually want scene coordinates, View is right choice too, because it knows transformation matrix. Coordinates go like this: Screen -> EditorWindow local -> EditorView local -> Scene transformed -> whatever item local transformed.
1,354,900
1,354,989
Resizing a char[] at run time
I need to resize a char array[size] to char array[new_size] at runtime. How can I do this?
ok, thanks for all the answers, I fixed my problem just by creating a new space for the new char array throwght a pointer... thanks
1,354,958
1,354,963
Memory leaks in C++ (via new+delete)
In order for an application to have no memory leaks, does the number of new in a C++ project match the number of delete?
If you mean do you need the same number of instances of delete in your source code as you have instances of new, then no. You can have objects newed in multiple places, but all these objects deleted by the same line of code. In fact this is a common idiom. Smart pointers, of varying types, generally take many different objects newed in many places in user code and delete them from a single place in library code. Edit Technically, every successfully memory allocation call needs to be matched with a dellocation call that takes the returned pointer from the original allocation call. Most new expressions result in a call to an operator new that allocates the memory and the constructs an object in the newly allocated memory. Using a delete expression destroys the object and causes a call to an operator delete that should free the allocated memory. There are new expressions that construct objects in pre-allocated memory (placement new). These should not be matched by a delete expression, but the pre-allocated memory may need to be deallocated in a way that corresponds to the original allocation.
1,354,985
1,355,001
VS C++ program only works when .exe is run from folder? [not VS debug]
Output from debug: File opened... File contents: Output from .exe (run via double click from /project/debug): File opened... File contents: line1 line2 etc. . . Source code: #include <iostream> #include <fstream> #include <regex> #include <string> #include <list> using namespace std; using namespace tr1; int main() { string line; list<string> dataList; ifstream myFile("test_data.txt"); if (! myFile) { cout << "Error opening file. \n"; return 0; } else { cout << "File opened... \n"; while( getline(myFile, line) ) { dataList.push_back(line); } } cout << "\n\n File contents:"; list<string>::iterator Iterator; for(Iterator = dataList.begin(); Iterator != dataList.end(); Iterator++) { cout << "\t" + *Iterator + "\n"; } getchar(); return 1; } thank you for your help! i now understand the problem, thank you. obviously, this also shows that this method of error handling for files is worthless. I have corrected that as well. Thanks again.
The way you've coded this line: ifstream myFile("test_data.txt"); means that the code is looking for the file in the current working directory. When you run outside the debugger that will be /project/debug (in your case), which is where the file presumably is. When you run inside the debugger that will (probably) be \project, which won't contain the file. You'll need to either have two copies of the file, hard code the full path to the file, or have some way of specifying the file at runtime.
1,355,167
1,355,256
Reading to end of file with istream_iterator and istream overload
I'm having some trouble reading data from a file into a vector of Orders. Code: #include <string> #include <vector> #include <fstream> #include <iostream> #include <iterator> using namespace std; class Purchase; class Order { public: string name; string address; vector<Purchase> items; }; class Purchase { public: string product_name; double unit_price; int count; Purchase() {} Purchase(string pn, double up, int c) :product_name(pn), unit_price(up), count(c) {} }; istream& operator>>(istream& in, Order& o) { string p_name; double u_price; int p_count; getline(in, o.name); getline(in, o.address); getline(in, p_name); in >> u_price >> p_count; o.items.push_back(Purchase(p_name, u_price, p_count)); return in; } ostream& operator<<(ostream& out, const Purchase& p) { out << p.product_name << '\n' << p.unit_price << '\n' << p.count << '\n'; return out; } ostream& operator<<(ostream& out, const Order& o) { out << '\n' << o.name << '\n' << o.address << '\n' << o.item << '\n'; return out; } int main() { cout << "Enter file to read orders from: \n"; string file; cin >> file; ifstream is(file.c_str()); istream_iterator<Order> ii(is); istream_iterator<Order> eos; ostream_iterator<Order> oo(cout); vector<Order> orders(ii, eos); copy(orders.begin(), orders.end(), oo); } I have 3 main questions. 1) When I take out the o.item bug in the ostream overload to test output, it only outputs the first entry in the file. The txt file is structured in groups of 5 lines of data that are supposed to be read into vector orders. Right now the txt file has 10 "orders", but it only reads the first one into the orders vector. I probably need to implement some kind of end of file operation, but I'm not sure how to do this with the istream overload and iterator. This is the biggest problem and if I can figure this out I think I'll probably be okay with the next 2 questions. 2) When that problem is fixed. I will need to deal with the output of o.item (the vector of Purchases in orders which currently can't be output because there is no element being specified). Obviously I need to specify the element to output and I've considered just using a static int and incrementing it, but this would need to be reset for every separate Order, which leads to question 3... 3) If the same name/address are read in as a previous read, I need the program to understand that it is the same "order" being read in and to simply add another object to that Order's Purchases vector rather than creating a new order. I'm thinking about using find() to check if that name already exists in order, and in that case doing nothing with the name/address inputs, but if there is a better way I'd like to know. Sorry if this is kind of long. If more explanation is needed I'd be happy to elaborate. Any help is appreciated. Thanks. P.S. Here is an example of input output at the moment if I specify the o.item output to be o.item[0]. Text file has: John Smith 117 One Tree Hill Trampoline 600.00 1 //... 9 more Orders like this Output is: John Smith 117 One Tree Hill Trampoline 600.00 1 //... Nothing after this....
Regarding question #3, you could use a multimap instead of a vector. First, assume you split your Order class up as follows: class Customer{ public: string name; string address; }; class Purchase { public: string product_name; double unit_price; int count; Purchase() {} Purchase(string pn, double up, int c) :product_name(pn), unit_price(up), count(c) {} }; class Order { Customer c; std::vector<Purchase> p; }; Now you can simply create a std::multimap<Customer, Purchase>. Adding a customer/purchase pair does exactly what you want: If the customer doesn't already exist, he is added, otherwise the purchase is just added to the existing customer. Of course, for this to work, you need to define a comparer as well. Simplest way might just be to define operator < for the Customer class. Implement it by comparing the name and disregarding the address. As for your other questions, avoid mixing getline and stream_iterators. It's not wrong per se, but it gets pretty tricky because getline reads a line at a time, and stream iterators just read to the next whitespace. Honestly, the C++ IOStreams library is pretty awful to use in general. Since your data format is already cleanly line-separated already, I'd probably just ditch the stream iterators and use getline everywhere.
1,355,187
1,357,350
python object to native c++ pointer
Im toying around with the idea to use python as an embedded scripting language for a project im working on and have got most things working. However i cant seem to be able to convert a python extended object back into a native c++ pointer. So this is my class: class CGEGameModeBase { public: virtual void FunctionCall()=0; virtual const char* StringReturn()=0; }; class CGEPYGameMode : public CGEGameModeBase, public boost::python::wrapper<CGEPYGameMode> { public: virtual void FunctionCall() { if (override f = this->get_override("FunctionCall")) f(); } virtual const char* StringReturn() { if (override f = this->get_override("StringReturn")) return f(); return "FAILED TO CALL"; } }; Boost wrapping: BOOST_PYTHON_MODULE(GEGameMode) { class_<CGEGameModeBase, boost::noncopyable>("CGEGameModeBase", no_init); class_<CGEPYGameMode, bases<CGEGameModeBase> >("CGEPYGameMode", no_init) .def("FunctionCall", &CGEPYGameMode::FunctionCall) .def("StringReturn", &CGEPYGameMode::StringReturn); } and the python code: import GEGameMode def Ident(): return "Alpha" def NewGamePlay(): return "NewAlpha" def NewAlpha(): import GEGameMode import GEUtil class Alpha(GEGameMode.CGEPYGameMode): def __init__(self): print "Made new Alpha!" def FunctionCall(self): GEUtil.Msg("This is function test Alpha!") def StringReturn(self): return "This is return test Alpha!" return Alpha() Now i can call the first to functions fine by doing this: const char* ident = extract< const char* >( GetLocalDict()["Ident"]() ); const char* newgameplay = extract< const char* >( GetLocalDict()["NewGamePlay"]() ); printf("Loading Script: %s\n", ident); CGEPYGameMode* m_pGameMode = extract< CGEPYGameMode* >( GetLocalDict()[newgameplay]() ); However when i try and convert the Alpha class back to its base class (last line above) i get an boost error: TypeError: No registered converter was able to extract a C++ pointer to type class CGEPYGameMode from this Python object of type Alpha I have done alot of searching on the net but cant work out how to convert the Alpha object into its base class pointer. I could leave it as an object but rather have it as a pointer so some non python aware code can use it. Any ideas?
Thanks to Stefan from the python c++ mailling list, i was missing super(Alpha, self).__init__() from the constructor call meaning it never made the parent class. Thought this would of been automatic :D Only other issue i had was saving the new class instance as a global var otherwise it got cleaned up as it went out of scope. So happy now
1,355,342
1,355,382
C++ creating and collecting structs in a loop
I want to create a struct from data harvested by line from a file. Each line necessitates a new struct, and the lines are accessed in a while loop. In C# I did this by creating anonymous structs and adding them to a list of structs. C++ would seem not to allow anonymous structs. I tried naming them with an incrementing variable, but this did not work, as the variable name was taken literally - regardless, I would prefer not to be forced to use this method as I hate the idea of irrelevant names. I suppose I could name the struct by a unique property, but, obviously, I would rather use a property as. . . a property. Besides, what if they are not all necessarily unique? Can someone suggest something or explain something that I am missing? Thanks! in c# (psuedo: public static List<Referral> Referrals = new List<Referral>(); //in loop: var NewReferral = new Referral(referringURL.Trim(), referringWords.Trim().ToLower() , 1); if ( NewReferral.URL == referringURL.Trim() ) {Referrals.Add(NewReferral); in c++: list<CollectedData> AllData; ifstream myFile("test_data.txt"); if (myFile.fail()) {cout << "Error opening file"; return 0;} else { cout << "File opened... \n"; while( getline(myFile, line) ) { struct CollectedData; //add property values //add struct to struct list } } (please do go into detail about when they automatically delete, it probably won't be helpful, but i'd like to know. thanks!)
Your C++ looks to be on the right track, aside from two things. One, you have to define the form of a CollectedData struct somewhere, and two you have to give a name to your struct variable: For example, if you define the CollectedData struct like so struct CollectedData { int field1; std::string field2; bool field3; // etc }; Then in your inner loop you can do this while( getline(myFile, line) ) { CollectedData lineData; //add property values lineData.field1 = /*whatever*/; lineData.field2 = /*whatever*/; lineData.field3 = /*whatever*/; //add struct to struct list AllData.push_back(lineData); } Each time through the loop a new CollectedData object is created, and its fields are filled in, then a copy of it is pushed into the AllData list, and then finally the object is automatically destroyed (remember a copy still exists in the list). Detail About When Objects Are Destroyed C++ has three sorts of storage: static, automatic, and dynamic. Static-storage objects exist for the whole lifetime of the program. Any object created outside of a class or function is static (i.e. globals are static). Same goes for anything declared inside of a class or function with the 'static' keyword. Dynamic-storage objects are objects created with keyword 'new' (or with malloc(), but that is a C-ism that should generally be avoided in C++ unless really necessary). Dynamic-storage objects are objects whose lifetime is managed manually by the programmer. A dynamically-stored object will continue to exist until you destroy it with keyword "delete". Note that the only way you can access a dynamically-stored object is through a pointer or a reference. If you're not using a pointer or reference, it isn't dynamic (but a pointer/reference can also refer to a non-dynamic object). Automatic-storage objects are your regular variables: members variables of structs and classes, and local variables (including parameters) in methods and functions. Automatic-storage objects defined inside functions are created when the line of code that defines them is run. They are automatically destroyed when they "go out of scope", that is, when the block that they are declared inside of terminates. In general, a "block" is a set of braces: {}. So, anything created inside of a function is destroyed when the function returns, and likewise anything created inside of a while-loop's body is automatically destroyed when the loop reaches its end (regardless of whether it terminates or iterates again). Automatic-storage objects defined as members of classes or structs are created when the object that contains them as members is created, and destroyed when the object that contains them as members is destroyed. (I used the term "object" repeatedly above, but the same rules apply to fundamental types like int, char, bool, etc)
1,355,446
1,355,932
Get visible rectangle of QGraphicsView?
I've been pulling my hair out with this one for hours. There's a thread here about it, but nothing seems to be working. QGraphicsView::rect() will return the width and height, but the left and top values aren't set properly (always 0 -- ignoring the scrolled amount). I want it in scene coordinates, but it should be easy enough to translate from any system. I have no idea what horizontalScrollBar()->value() and vert are returning...seems to be meaningless jibberish. @fabrizioM: // created here void EditorWindow::createScene() { m_scene = new EditorScene(this); m_view = new EditorView(m_scene); setCentralWidget(m_view); connect(m_scene, SIGNAL(mousePosChanged(QPointF)), this, SLOT(mousePosChanged(QPointF))); } /// with this constructor EditorView::EditorView(QGraphicsScene* scene, QWidget* parent) : QGraphicsView(scene, parent) { setRenderHint(QPainter::Antialiasing); setCacheMode(QGraphicsView::CacheBackground); setViewportUpdateMode(QGraphicsView::FullViewportUpdate); setDragMode(QGraphicsView::NoDrag); scale(1.0, -1.0); // flip coordinate system so that y increases upwards fitInView(-5, -5, 10, 10, Qt::KeepAspectRatio); setInteractive(true); setBackgroundBrush(QBrush(QColor(232,232,232), Qt::DiagCrossPattern)); }
Nevermind. Came up with this, which seems to work. QRectF EditorView::visibleRect() { QPointF tl(horizontalScrollBar()->value(), verticalScrollBar()->value()); QPointF br = tl + viewport()->rect().bottomRight(); QMatrix mat = matrix().inverted(); return mat.mapRect(QRectF(tl,br)); }
1,355,531
1,355,539
C++ How to loop through a list of structs and access their properties
I know I can loop through a list of strings like this: list<string>::iterator Iterator; for(Iterator = AllData.begin(); Iterator != AllData.end(); Iterator++) { cout << "\t" + *Iterator + "\n"; } but how can I do something like this? list<CollectedData>::iterator Iterator; for(Iterator = AllData.begin(); Iterator != AllData.end(); Iterator++) { cout << "\t" + *Iterator.property1 + "\n"; cout << "\t" + *Iterator.property2 + "\n"; } or if someone can explain how to do this with a for_each loop, that would be very helpful as well, but it seemed more complicated from what I've read. thank you so much
It's as easy as Iterator->property. Your first attempt is almost correct, it just needs some parentheses due to operator precedence: (*Iterator).property In order to use for_each, you would have to lift the cout statments into a function or functor like so: void printData(AllDataType &data) { cout << "\t" + data.property1 + "\n"; cout << "\t" + data.property2 + "\n"; } for_each(AllData.begin(), AllData.end(), printData);
1,355,564
1,355,585
Smiley face when assigning improper value type to struct property!
I am somewhat wondering if I am losing my mind, but I swear to you, this code outputs smiley faces as the .name values!! what in the world is going on? Thus far it seems to only work when the value is 1, anything else properly gives errors. I realize the code is flawed -> I do not need help with this. #include <iostream> #include <fstream> #include <regex> #include <string> #include <list> using namespace std; using namespace tr1; struct CollectedData { public: string name; float grade; }; int main() { string line; list<CollectedData> AllData; int count; ifstream myFile("test_data.txt"); if (myFile.fail()) {cout << "Error opening file"; return 0;} else { cout << "File opened... \n"; while( getline(myFile, line) ) { CollectedData lineData; lineData.name = 1; lineData.grade = 2; AllData.push_back(lineData); } } cout << "\n\n File contents: \n"; list<CollectedData>::iterator Iterator; for(Iterator = AllData.begin(); Iterator != AllData.end(); Iterator++) { cout << "\t" << (*Iterator).name << " - "; cout << "\t" << (*Iterator).grade << "\n"; } getchar(); return 1; } :-) http://img21.imageshack.us/img21/4600/capturekjc.jpg I KNOW THAT THE CODE IS USELESS, I WANT TO KNOW WHY IT IS GIVING ME SMILEY FACES INSTEAD OF ERRORS comforting. . . mocking
The smiling face is the character with ASCII value 1. Not sure why, but apparently your compiler decided to treat it as a char, so you get the smiley.
1,355,803
1,355,862
Why is the C++ syntax so complicated?
I'm a novice at programming although I've been teaching myself Python for about a year and I studied C# some time ago. This month I started C++ programming courses at my university and I just have to ask; "why is the C++ code so complicated?" Writing "Hello world." in Python is as simple as "print 'Hello world.'" but in C++ it's: # include <iostream> using namespace std; int main () { cout << "Hello world."; return 0; } I know there is probably a good reason for all of this but, why... ... do you have to include the <iostream> everytime? Do you ever not need it? ... same question for the standard library, when do you not need std::*? ... is the "main" part a function? Do you ever call the main function? Why is it an integer? Why does C++ need to have a main function but Python doesn't? ... do you need "std::cout << "? Isn't that needlessly long and complicated compared to Python? ... do you need to return 0 even when you are never going to use it? This is probably because I'm learning such basic C++ but every program I've made so far looks like this, so I have to retype the same code over and over again. Isn't that redundant? Couldn't the compiler just input this code itself, since it's always the same (i.e. afaik you always include <iostream>, std, int main, return 0)
C++ is a more low-level language that executes without the context of an interpreter. As such, it has many different design choices than does Python, because C++ has no environment which it can rely on to manage information like types and memory. C++ can be used to write an operating system kernel where there is no code running on the machine except for the program itself, which means that the language (some library facilities are not available for so-called freestanding implementations) must be self-contained. This is why C++ has no equivalent to Python's eval, nor a means of determining members, etc. of a class, nor other features that require an execution environment (or a massive overhead in the program itself instead of such an environment) For your individual questions: do you have to include the <iostream> everytime? Do you ever not need it? #include <iostream> is the directive that imports the <iostream> header into your program. <iostream> contains the standard input/output objects - in particular, cout. If you aren't using standard I/O objects (for instance, you use only file I/O, or your program uses a GUI library, or are writing an operating system kernel), you do not need <iostream> same question for the standard library, when do you not need std::*? std is the namespace containing all of the standard library. using namespace std; is sort of like from std import *, whereas a #include directive is (in this regard) more like a barebones import std statement. (in actual fact, the mechanism is rather different, because C++ does not use using namespace std; to automatically lookup objects in std; the using-directive only imports the names into the global namespace.) I'll note here that using-directives (using namespace) are frequently frowned upon in C++ code, as they import a lot of names and can cause name clashes. using-declarations (using std::cout;) are preferred when possible, as is limiting the scope of a using-directive (for instance, to one function or to one source file). Don't ever put using namespace in a header without good reason. is the "main" part a function? Do you ever call the main function? Why is it an integer? Why does C++ need to have a main function but Python doesn't? main is the entry point to the program - where execution starts. In Python, the __main__ module serves the same purpose. C++ does not execute code outside a defined function like Python does, so its entry point is a function rather than a module. do you need "std::cout << "? Isn't that needlessly long and complicated compared to Python? std::cout is only needed if you don't import the cout name into the global namespace, either by a using-directive (using namespace std;) or by a using-declaration (using std::cout). In this regard, it is once again much like the distinction between Python's import std and from std import * or from std import cout. The << is an overloaded operator for standard stream objects. cout << value calls cout's function to output value. Python needs no such extra code because print is built into the language; this does not make sense for C++, where there may not even be an operating system, much less an I/O library. do you need to return 0 even when you are never going to use it? No. main (and no other function) has an implicit return 0; at the end. The return value of main (or, if the exit function is called, the value passed to it) is passed back to the operating system as the exit code. 0 indicates the program successfully executed - that it encountered no errors, etc. If an error is encountered, a non-zero value should be returned (or passed to exit).
1,355,877
1,356,128
How to pass 2D map as a parameter to a function in c++?
I have a map like std::map< int, int> random[50]; How can i pass this map as a parameter to a function say Perform()? Thanks in advance.
void Perform( std::map< int, int > r[], size_t numElements ); or void Perform( std::map< int, int >* r, size_t numElements ); Then, either way, call Perform( random, 50 ); Edit: this can also be called as follows for any const array size. Perform( random, sizeof( random ) / sizeof ( random[0] ) );
1,356,204
1,356,219
private typedef visible in derived class
I have a small problem with my compiler (VC++ 6.0). In my opinion, such a code should cause error; class Base { private: typedef int T; }; class Derived : private Base // Here the Base class can be inherited publicly as well. It does not play any role { public: T z; }; int main() { Derived obj; obj.z = 7; return 0; } This code snippet is compiled and run under VC++ 6.0 without any problem. Regarding SW-Design, this code is not perfect. None of the class member members should be declared as public. But I am not interested in this aspect. My problem is with typedef. The typedef is declared in Base class as private. From my point of C++ understanding, this typedef must not be visible either to Derived class or to main() function. But both see them perfectly. Does anybody have an explanation to this phenomenon? Thanks in advance Necip
This behavior is a non conformance in VC++6.0, you should have got an error when defining Derived::z. (Excepted if you have business reasons to use it, there are other choices technically preferable to VC++6.0 which is old).
1,356,210
1,356,930
How to design a C++ class?
I wrote a application in MFC with C++. I need to write a class which can save all the data loaded from the database, These data might contain every kind of data type, such as int, string, byte, boolean, datetime and so on. We might filter, exchange columns, or sort on these data. For example: int int string bool double float .... string 0 1 "a" false 3.14 3.0 "b" 1 2 "5" true 3.22 4 "c" Note: We didn't use SQL to sort or filter, since we have our consideration. We have wrote the following class, could someone have better suggestion, please write a sample class for use, thanks in advance! #ifndef __LIST_DATA_MODEL_H__ #define __LIST_DATA_MODEL_H__ #include <vector> using std::vector; ///implement a pure virtual base class; parameters of function is a void pointer, class FieldType { public: enum { TypeChar = 0, TypeString = 1, TypeBool = 2, TypeShort = 3, TypeUShort = 4, TypeInt = 5, TypeUInt = 6, TypeLong = 7, TypeULong = 8, TypeLongLong = 9, TypeULongLong = 10, TypeFloat = 11, TypeDouble = 12 }; }; template <typename _ValueType, typename _SyncType> class Column { protected: CString m_szFieldName; vector<_ValueType> m_vValues; public: Column(); Column(CString szFieldName); Column(const Column& other); virtual ~Column(); public: virtual BOOL LoadData(...); public: ///This function will call LoadData function to re-load data, ///if subclass this class, please implement your LoadData function ///if you want additional operation when load data. CALLBACK BOOL Update(); public: const int ValueCount() const; const CString& FieldName() const; const _ValueType& ValueAt(int iPos) const; ///Before you call LoadData function or Update Function, the values will not updated; void SetFieldName(const CString& szFieldName); void SetValue(const _ValueType& val, int iPos); }; template<class _Type> class DataItem { protected: _Type _value; public: DataItem(); DataItem(const DataItem& other) { _value = other._value; }; DataItem(const _Type& val) { _value = val; }; virtual ~DataItem() { }; public: const _Type& GetValue() { return _value; }; void SetValue(const _Type& value) { _value = value; }; void ResetValue() { _value = _Type(); }; public: bool operator ==(DataItem& right) { return _value == right._value; }; bool operator <(const DataItem& right) { return _value < right._value; }; const DataItem& operator =(const DataItem& right) { if(this == &right) return *this; _value = right._value; return *this; }; virtual DataItem* Clone() { return new DataItem(*this); }; }; typedef DataItem<int> IntItem; typedef DataItem<float> FloatItem; typedef DataItem<double> DoubleItem; typedef DataItem<CString> StringItem; typedef DataItem<bool> BoolItem; typedef DataItem<TCHAR> CharItem; typedef DataItem<char> ByteItem; typedef DataItem<CString> CStringItem; #endif
I am wondering if you are emulating the DB behavior, then does it make sense to store the data in containers of 'type'? Since the data will be accessed via column-names, you need to have containers that store data-values for each column and have column-name to column-type mapping. Anyway if you want to store data along with its type then consider the following approach using 'stringization of enums':- Create your own enumeration constants for types. Like enum MYTYPE { MYINT, MYFLOAT, ...} Write-out the DB information after stringizing the data under each stringized-enum. Read the stringized-enum along with its data into a stringized container like std::vector<string>. Extract the actual enumeration-type from the stringized-enum and then using a simple switch case statement, covert the stringized-data to actual data. On how to create stringized enums and use them follow link here and here. The Macro's approach. Or you can use a templatized approcah which requires use of boost something like below (only a hint :-) ). template<typename ENUM> class Stringifier<ENUM, typename boost::enable_if<boost::is_enum<ENUM> >::type> { static const char * values[]; // array with the enum strings. static std::size_t size; // Number of elements of the ENUM string arrays. public: /// Global static instance of the Stringifier. static Stringifier & getInstance() { static Stringifier globalInstance; return globalInstance; } // Returns the string representation of the ENUM value \a e as a C string. // If string is not available an exception is thrown. virtual void str(ENUM const & e, std::string & s) const { if(e >= 0 && e < int(size)) s = values[e]; else // throw exception ; } // Returns the ENUM value of the string representation of an ENUM value if possible, // ENUM(0) otherwise or ENUM(size) if you like. virtual bool value(std::string const & str, ENUM & v) const { std::size_t i = 0; for(; i < size; ++i) if(values[i] == str) break; bool ok = (i != size); v = ok ? ENUM(i) : ENUM(0); return ok; } }; Use your enumeration as 'ENUM' in the above class. NOTE: Stringization kills performance. So this approach is slower.
1,356,510
1,384,801
Relational databases application
When developing an application which mostly interacts with a database, what is a good way to start? The application requires a lot of filtering based on user input, sorting and structuring.
The best way to start is by figuring out "user stories" (or "use cases" -- but the "story" approach tends to really work great and start dragging shareholder into the shared storytelling...!-); on top of that, designing the database schema as the best-normalized idea you can find to satisfy all data layer needs of the user stories. Thirdly, you may sketch layers such as views on top of the schema; fourthly, and optionally, triggers and stored procedures that might live in the DB to ensure consistency and ease of use for higher layers (but, no matter how strongly DBAs will push you towards those, don't accept their assurances that they're a MUST: they aren't -- if your storage layer is well designed in terms of normalization and maybe useful views on top, non-storage-layer functionality CAN always reside elsewhere, it's an issue of convenience and performance, NOT logical consistency, completeness, correctness). I think the business layer and user-experience layers should come after. I realize that's a controversial position, but my point is that the user stories (and implied business-rules that come with them) have ALREADY told you a LOT about the business and user layers -- so, "nailing down" (relatively speaking -- agility and "embrace change!" should always rule;-) the data storage layer is the next order of business, and refining ("drilling down") the higher layers can and should come after.
1,356,896
1,360,175
How to hide a string in binary code?
Sometimes, it is useful to hide a string from a binary (executable) file. For example, it makes sense to hide encryption keys from binaries. When I say “hide”, I mean making strings harder to find in the compiled binary. For example, this code: const char* encryptionKey = "My strong encryption key"; // Using the key after compilation produces an executable file with the following in its data section: 4D 79 20 73 74 72 6F 6E-67 20 65 6E 63 72 79 70 |My strong encryp| 74 69 6F 6E 20 6B 65 79 |tion key | You can see that our secret string can be easily found and/or modified. I could hide the string… char encryptionKey[30]; int n = 0; encryptionKey[n++] = 'M'; encryptionKey[n++] = 'y'; encryptionKey[n++] = ' '; encryptionKey[n++] = 's'; encryptionKey[n++] = 't'; encryptionKey[n++] = 'r'; encryptionKey[n++] = 'o'; encryptionKey[n++] = 'n'; encryptionKey[n++] = 'g'; encryptionKey[n++] = ' '; encryptionKey[n++] = 'e'; encryptionKey[n++] = 'n'; encryptionKey[n++] = 'c'; encryptionKey[n++] = 'r'; encryptionKey[n++] = 'y'; encryptionKey[n++] = 'p'; encryptionKey[n++] = 't'; encryptionKey[n++] = 'i'; encryptionKey[n++] = 'o'; encryptionKey[n++] = 'n'; encryptionKey[n++] = ' '; encryptionKey[n++] = 'k'; encryptionKey[n++] = 'e'; encryptionKey[n++] = 'y'; …but it's not a nice method. Any better ideas? PS: I know that merely hiding secrets doesn't work against a determined attacker, but it's much better than nothing… Also, I know about assymetric encryption, but it's not acceptable in this case. I am refactoring an existing appication which uses Blowfish encryption and passes encrypted data to the server (the server decrypts the data with the same key). I can't change the encryption algorithm because I need to provide backward compatibility. I can't even change the encryption key.
I'm sorry for long answer. Your answers are absolutely correct, but the question was how to hide string and do it nicely. I did it in such way: #include "HideString.h" DEFINE_HIDDEN_STRING(EncryptionKey, 0x7f, ('M')('y')(' ')('s')('t')('r')('o')('n')('g')(' ')('e')('n')('c')('r')('y')('p')('t')('i')('o')('n')(' ')('k')('e')('y')) DEFINE_HIDDEN_STRING(EncryptionKey2, 0x27, ('T')('e')('s')('t')) int main() { std::cout << GetEncryptionKey() << std::endl; std::cout << GetEncryptionKey2() << std::endl; return 0; } HideString.h: #include <boost/preprocessor/cat.hpp> #include <boost/preprocessor/seq/for_each_i.hpp> #include <boost/preprocessor/seq/enum.hpp> #define CRYPT_MACRO(r, d, i, elem) ( elem ^ ( d - i ) ) #define DEFINE_HIDDEN_STRING(NAME, SEED, SEQ)\ static const char* BOOST_PP_CAT(Get, NAME)()\ {\ static char data[] = {\ BOOST_PP_SEQ_ENUM(BOOST_PP_SEQ_FOR_EACH_I(CRYPT_MACRO, SEED, SEQ)),\ '\0'\ };\ \ static bool isEncrypted = true;\ if ( isEncrypted )\ {\ for (unsigned i = 0; i < ( sizeof(data) / sizeof(data[0]) ) - 1; ++i)\ {\ data[i] = CRYPT_MACRO(_, SEED, i, data[i]);\ }\ \ isEncrypted = false;\ }\ \ return data;\ } Most tricky line in HideString.h is: BOOST_PP_SEQ_ENUM(BOOST_PP_SEQ_FOR_EACH_I(CRYPT_MACRO, SEED, SEQ)) Lets me explane the line. For code: DEFINE_HIDDEN_STRING(EncryptionKey2, 0x27, ('T')('e')('s')('t')) BOOST_PP_SEQ_FOR_EACH_I(CRYPT_MACRO, SEED, SEQ) generate sequence: ( 'T' ^ ( 0x27 - 0 ) ) ( 'e' ^ ( 0x27 - 1 ) ) ( 's' ^ ( 0x27 - 2 ) ) ( 't' ^ ( 0x27 - 3 ) ) BOOST_PP_SEQ_ENUM(BOOST_PP_SEQ_FOR_EACH_I(CRYPT_MACRO, SEED, SEQ)) generate: 'T' ^ ( 0x27 - 0 ), 'e' ^ ( 0x27 - 1 ), 's' ^ ( 0x27 - 2 ), 't' ^ ( 0x27 - 3 ) and finally, DEFINE_HIDDEN_STRING(EncryptionKey2, 0x27, ('T')('e')('s')('t')) generate: static const char* GetEncryptionKey2() { static char data[] = { 'T' ^ ( 0x27 - 0 ), 'e' ^ ( 0x27 - 1 ), 's' ^ ( 0x27 - 2 ), 't' ^ ( 0x27 - 3 ), '\0' }; static bool isEncrypted = true; if ( isEncrypted ) { for (unsigned i = 0; i < ( sizeof(data) / sizeof(data[0]) ) - 1; ++i) { data[i] = ( data[i] ^ ( 0x27 - i ) ); } isEncrypted = false; } return data; } data for "My strong encryption key" looks like: 0x00B0200C 32 07 5d 0f 0f 08 16 16 10 56 10 1a 10 00 08 2.]......V..... 0x00B0201B 00 1b 07 02 02 4b 01 0c 11 00 00 00 00 00 00 .....K......... Thank you very much for your answers!
1,357,374
1,357,406
locale-dependent ordering for std::string
I am trying to compare std::strings in a locale-dependent manner. For ordinary C-style strings, I've found strcoll, which does exactly what I want, after doing std::setlocale #include <iostream> #include <locale> #include <cstring> bool cmp(const char* a, const char* b) { return strcoll(a, b) < 0; } int main() { const char* s1 = "z", *s2 = "å", *s3 = "ä", *s4 = "ö"; std::cout << (cmp(s1,s2) && cmp(s2,s3) && cmp(s3,s4)) << "\n"; //Outputs 0 std::setlocale(LC_ALL, "sv_SE.UTF-8"); std::cout << (cmp(s1,s2) && cmp(s2,s3) && cmp(s3,s4)) << "\n"; //Outputs 1, like it should return 0; } However, I'd like to have this behaviour for std::string as well. I could just overload operator< to do something like bool operator<(const std::string& a, const std::string& b) { return strcoll(a.c_str(), b.c_str()); } but then I'd have to worry about code using std::less and std::string::compare, so it doesn't feel right. Is there a way to make this kind of collation work for strings in a seamless manner?
operator() of std::locale is just what you are searching. To get the current global locale, just use the default constructor.
1,357,569
1,372,310
Using Crypto++ generated RSA keys on OpenSSL
Is there a way to use the RSA keys I've generated with the Crypto++ API in OpenSSL? What I am looking for is a way to store the keys in a format that both Crypto++ and OpenSSL can easily open them. I'm writing a licensing scheme and would want to verify signatures and decrypt files using the Crypto++ API, but to generate the license files I would want to use a web interface (probably using PHP, which only supports OpenSSL) to generate and encrypt/sign the licenses. I would write both applications using Crypto++ and call it from the PHP, but since the private key will be stored in a encrypted form, a password must be passed to the application and passing it on the command line doesn't seems to be a good idea to me.
Both Crypto++ and OpenSSL can handle PKCS#8 encoded keys. In crypto++, you can generate keys and convert to PKCS#8 buffer like this, AutoSeededRandomPool rng; RSAES_OAEP_SHA_Decryptor priv(rng, 2048); string der; StringSink der_sink(der); priv.DEREncode(der_sink); der_sink.MessageEnd(); // der.data() is the bytes you need Now you just need to pass the bytes to PHP. You can save it in a file, send in a message. The only gotcha is that PHP's OpenSSL interface only accepts PEM encoded PKCS#8. You can easily convert DER-encoded buffer into PEM like this in PHP, <?php function pkcs8_to_pem($der) { static $BEGIN_MARKER = "-----BEGIN PRIVATE KEY-----"; static $END_MARKER = "-----END PRIVATE KEY-----"; $value = base64_encode($der); $pem = $BEGIN_MARKER . "\n"; $pem .= chunk_split($value, 64, "\n"); $pem .= $END_MARKER . "\n"; return $pem; } ?> You can also convert PKCS#8 to PEM in C++ if you prefer. The algorithm is very simple as you can see from the PHP code. OpenSSL is so prevalent nowadays. I don't see any reason to use Crypto++ for common crypto applications like this.
1,357,733
1,357,747
Best way to display output of pattern search on text files?
first question here! I'm writing a grep type program for Windows, just for fun (using Mingw). It works well for text files where lines are terminated by '\n'. I'm using fstream::getline() for this. But I also need to be able to search files containing just a giant block of text with no line numbers. fstream::getline() fails here. Is there any function to read N characters into a buffer from such a file? Also, what's the best way to tell the user where the match was found in such a file?
istream::read() will read an arbitrary number of characters from an istream. As for where in the file it was found, a line number and character offset might be a good way to go.
1,357,807
1,357,937
when is better to use c++ template?
right now i am learning C++, and now I know the basic concept of template, which act just like a generic type, and i found almost every c++ program used template, So i really want to know when are we supposed to use template ? Can someone conclude your experience for me about c++ template ? When will you consider to use template ? Supplement: if we defined such function template <class myType> myType GetMax (myType a, myType b) { return (a>b?a:b); } but we want to pass a object(self-defined class) for comparison, how can we implement ? Supplement2: in the answer below, someone have wrote this sample code template <class myType> const myType& GetMax (const myType& a, const myType& b) { return (a<b?b:a); } template <class myType, class Compare> const myType& GetMax (const myType& a, const myType& b, Compare compare) { return (compare(a,b)?b:a); } is this correct ? can we just pass a function name as a parameter of class myType ?
Re: supplement. If you want to pass a comparison function, you could provide another overload: template <class myType> const myType& GetMax (const myType& a, const myType& b) { return (a<b?b:a); } template <class myType, class Compare> const myType& GetMax (const myType& a, const myType& b, Compare compare) { return (compare(a,b)?b:a); } Samle usage: to compare C-style strings: bool c_strings_less(const char* a, const char* b) { return std::strcmp(a, b) < 0; //is a less than b } const char* greater = GetMax("hello", "world", c_strings_less); This is how the std::max algorithm works. (I also made a few modifications, e.g it is customary in C++ that predicates define "less-than" comparison.) Or if you asked, how GetMax would work for arbitrary user-defined types, then those must overload operator> or your function would result in a compile error.
1,357,982
1,358,124
gvim :make command does not work
I am under a Unix environment, working in C++. I'm opening gvim from a directory in which a makefile called "Makefile" exists. When I try to use ":make" from within vim, I get: shell returned 2 (1 of 1): make: *** No targets specified and no makefile found. Stop.
Can you check the following options? :set shell? :set shelltype? Finally, check the contents of your shell login file. For example, if your shell is bash, check ~/.bashrc. Does this file contain something like the following? cd ~ Or: cd /home/${USERNAME} where ${USERNAME} is (obviously) your username.
1,358,400
1,358,622
What is external linkage and internal linkage?
I want to understand the external linkage and internal linkage and their difference. I also want to know the meaning of const variables internally link by default unless otherwise declared as extern.
When you write an implementation file (.cpp, .cxx, etc) your compiler generates a translation unit. This is the source file from your implementation plus all the headers you #included in it. Internal linkage refers to everything only in scope of a translation unit. External linkage refers to things that exist beyond a particular translation unit. In other words, accessible through the whole program, which is the combination of all translation units (or object files).
1,358,427
1,358,443
Function which returns an unknown type
class Test { public: SOMETHING DoIt(int a) { float FLOAT = 1.2; int INT = 2; char CHAR = 'a'; switch(a) { case 1: return INT; case 2: return FLOAT; case 3: return CHAR; } } }; int main(int argc, char* argv[]) { Test obj; cout<<obj.DoIt(1); return 0; } Now, using the knowledge that a = 1 implies that I need to return an integer, etc., is there anyway Doit() can return a variable of variable data type? Essentially, with what do I replace SOMETHING ? PS: I'm trying to find a an alternative to returning a structure/union containing these data types.
You can use boost::any or boost::variant to do what you want. I recommend boost::variant because you know the collection of types you want to return. This is a very simple example, though you can do much more with variant. Check the reference for more examples :) #include "boost/variant.hpp" #include <iostream> typedef boost::variant<char, int, double> myvariant; myvariant fun(int value) { if(value == 0) { return 1001; } else if(value == 1) { return 3.2; } return 'V'; } int main() { myvariant v = fun(0); std::cout << v << std::endl; v = fun(1); std::cout << v << std::endl; v = fun(54151); std::cout << v << std::endl; } The output: 1001 3.2 V I would use boost::variant instead of a union because you can't use non-POD types inside union. Also, boost::any is great if you don't know the type you are dealing with. Otherwise, I would use boost::variant because it is much more efficient and safer. Answering the edited question: If you don't want to ship Boost with your code, take a look at bcp. The description of bcp from the same link: The bcp utility is a tool for extracting subsets of Boost, it's useful for Boost authors who want to distribute their library separately from Boost, and for Boost users who want to distribute a subset of Boost with their application. bcp can also report on which parts of Boost your code is dependent on, and what licences are used by those dependencies.
1,358,508
1,358,616
referencing a function's arguments by position?
I'm not sure I know how to ask this. say I have a function void myFunc ( int8 foo, float bar, int whatever ) { ... } is there a quick way of referencing a particular argument by its position? void myFunc ( float foo, float bar, float whatever ) { float f; f = ARG[1]; // f now equals bar } something to that effect? Follow up: Thank you for your answers folks. I guess I'm going about it wrong. I find it odd that c++ doesn't allow for this, as perl and some psuedo languages (I'm thinking in particular of AutoIt) do. So as for "why"? Just to use a simple loop to go through them. I recognize that there are a myriad of better ways to achieve this in normal circumstances, but I was trying my darndest to not modify anyone's code outside of my little world. In other words I don't have control over the calling code. It is shoving the inputs down my throat and I have to manage them as best as possible. So I can't just loop before calling my function. Anyway, it was clearly going to be a mess and there weren't that many variables so I just duplicated code. No biggy. Thanks for the comments and interesting suggestions.
If it really seems like what you need is a parameter array of values of the same type instead of explicitly named parameters, then you can just pass an array as a parameter. void myFunc ( float foo[3] ) { float bar; bar = foo[1]; } That can be inefficient if your array is much longer, so a better solution would be using a const reference like this: void myFunc ( const float & foo[3] ) { float bar; bar = foo[1]; } Or like so many c++ questions on this site, the best solution is to use a std::vector void myFunc ( const std::vector<float> & foo ) { float bar; bar = foo[1]; }
1,358,748
1,359,073
Visual Studio 2008 Profiler - Instrumented produces strange results
I run the Visual Studio 2008 profiler on a "RelDebug" build of my app. Optimizations are on, but inlining is only moderate, stack frames are present, and symbols are emitted. In other words, RelDebug is a somewhat optimized build that can be debugged (although the usual Release caveats about inspecting variables applies). I run both the Sampling, and the Instrumented profiler on separate runs. Result? The Sampling profiler produces a result that looks reasonable. However when I look at the Instrumented profiler results, I see functions that should not even be near the top of the list, coming out up to. For example, a function like "SetFont" that consists of only 1 line assigning the height to a class member. Or "SetClipRect" that merely assigns a rectangle. Of course I am looking at "Exclusive" stats (i.e. minus children). This happen to anyone else? It always seems to happen once my application has grown to a certain size. It makes the instrumented profiler useless at that point. I figured out the problem. Both the Visual Studio 2008 and the Visual Studio 2010 profilers are mediocre (to put it politely). I bought Intel C++ Studio which comes with vTune Amplifier (a profiler). Using the Intel profiler on the exact same code I was able to get profiler results that actually made sense.
You say "of course you are looking at Exclusive". Look at inclusive stats. In all but the simplest programs or algorithms, nearly all the time is spent in subroutines and functions, so if you've got a performance problem, it most likely consists of calls you didn't know were time-hogs. The method I rely on is this. Assuming you are trying to find out what you could fix to make the code faster, it will find it, while not wasting your time with high-precision statistics about things that are not problems.
1,359,003
1,360,394
svg example in C/C++
Can someone provide an example of how to load a .svg file and display it using C/C++ and any library? I'm wondering if you will use SDL, cairo, or what.
As Pavel put it, QtSvg is the way to go i believe. It is easier to use but in our team we have faced performance issues with QtSvg especially on Linux. So we decided to directly parse the SVG file XML by hand and render it using Qt itself. This turned out to be much faster. pseudocode:- // Read the SVG file using XML parser (SAX) void SvgReader::readFile() { QFile file(<some svg filename>); if (!file.open(QFile::ReadOnly | QFile::Text)) { qWarning("Cannot open file"); return; } QString localName; QXmlStreamAttributes attributes; pXml = new QXmlStreamReader(&file); pXml->setNamespaceProcessing(false); while (!pXml->atEnd()) { switch (pXml->readNext()) { case QXmlStreamReader::StartElement: localName = pXml->name().toString(); if (localName.compare(<some element path>) == 0) { attributes = pXml->attributes(); QStringRef data = attributes.value(<some attribute name>); // parse/use your data; } // similarly other case statements } } }
1,359,172
1,359,212
VS2008 C++ Compiler error?
this compiles :-) string name; name = 1; this does not: string name = 1; any thoughts? I know that this is wrong. . . that is not the point. The first gives a smiley face.
The first compiles because the assignment operator is called what has one signature of "string& operator= ( char c )" and the compiler can convert 1 into a char. The second won't compile because it calls the copy constructor which has no compatible signature.
1,359,620
1,360,028
Save bitmap to video (libavcodec ffmpeg)
I'd like to convert a HBitmap to a video stream using libavcodec. I get my HBitmap using: HBITMAP hCaptureBitmap =CreateCompatibleBitmap(hDesktopDC, nScreenWidth, nScreenHeight); SelectObject(hCaptureDC,hCaptureBitmap); BitBlt(hCaptureDC,0,0,nScreenWidth,nScreenHeight,hDesktopDC,0,0,SRCCOPY); And I'd like to convert it to YUV (which is required by the codec i'm using). For that I use: SwsContext *fooContext = sws_getContext(c->width,c->height,PIX_FMT_BGR32, c->width,c->height,PIX_FMT_YUV420P,SWS_FAST_BILINEAR,NULL,NULL,NULL); uint8_t *movie_dib_bits = reinterpret_cast<uint8_t *>(bm.bmBits) + bm.bmWidthBytes * (bm.bmHeight - 1); int dibrowbytes = -bm.bmWidthBytes; uint8_t* data_out[1]; int stride_out[1]; data_out[0] = movie_dib_bits; stride_out[0] = dibrowbytes; sws_scale(fooContext,data_out,stride_out,0,c->height,picture->data,picture->linesize); But this is not working at all... Any idea why ? Or how could I do it differently ? Thank you !
I am not familiar with the stuff you are using to get the bitmap, but assuming it is correct and you have a pointer to the BGR 32-bit/pixel data, try something like this: uint8_t* inbuffer; int in_width, in_height, out_width, out_height; //here, make sure inbuffer points to the input BGR32 data, //and the input and output dimensions are set correctly. //calculate the bytes needed for the output image int nbytes = avpicture_get_size(PIX_FMT_YUV420P, out_width, out_height); //create buffer for the output image uint8_t* outbuffer = (uint8_t*)av_malloc(nbytes); //create ffmpeg frame structures. These do not allocate space for image data, //just the pointers and other information about the image. AVFrame* inpic = avcodec_alloc_frame(); AVFrame* outpic = avcodec_alloc_frame(); //this will set the pointers in the frame structures to the right points in //the input and output buffers. avpicture_fill((AVPicture*)inpic, inbuffer, PIX_FMT_BGR32, in_width, in_height); avpicture_fill((AVPicture*)outpic, outbuffer, PIX_FMT_YUV420P, out_width, out_height); //create the conversion context SwsContext* fooContext = sws_getContext(in_width, in_height, PIX_FMT_BGR32, out_width, out_height, PIX_FMT_YUV420P, SWS_FAST_BILINEAR, NULL, NULL, NULL); //perform the conversion sws_scale(fooContext, inpic->data, inpic->linesize, 0, in_height, outpic->data, outpic->linesize); //encode the frame here... //free memory av_free(outbuffer); av_free(inpic); av_free(outpic); Of course, if you are going to be converting a sequence of frames, just make your allocations once at the beginning and deallocations once at the end.
1,359,703
1,359,759
custom data iostream
I have a data structure defined as struct myDataStruct { int32_t header; int16_t data[8]; } and I want to take a character stream and turn it into a myData stream. What stream class should I extend? I would like to create a custom stream class so that I can do things like myDataStruct myData; myDataStruct myDataArray[10]; myDataStream(ifstream("mydatafile.dat")); myDataStream.get(myData); myDataStream.read(myDataArray, 10);
Instead of myDataStream.get(myData), what you do is overload operator>> for your data type: std::istream& operator>>(std::istream& is, myDataStruct& obj) { // read from is into obj return is; } If you want to read into an array, just write a loop: for( std::size_t idx=0; idx<10; ++idx ) { myDataStruct tmp; if( is >> tmp ) myDataArray[idx] = tmp; else throw "input stream broken!"; } Using a function template, you should also able to overload the operator for arrays on the right-hand side (but this I have never tried): template< std::size_t N > std::istream& operator>>(std::istream& is, myDataStruct (&myDataArray)[N]) { // use loop as above, using N instead of the 10 } But I can't decide whether this is gorgeous or despicable.
1,359,903
1,736,663
free non-gpl data compression libraries
i'm writing project that stores data, so i need to compress it. I've tried zlib but it's bottleneck of my project. So maybe there is faster solution. I don't need a great compress ratio, but i'm looking for really fast compression. Are there any other data compression libraries except zlib, that are really free and can be used in proprietary software (project, i'm working on, isn't GPL-based). My project is on C++ and I need to compress char* arrays of text.
Here are a few: FastLZ -- fast and lightweight, MIT license unless you want to use it under a GPL license LZJB -- also fast and pretty lightweight, used as default compression algorithm for Sun's ZFS
1,360,163
1,360,179
Problem with file loop and reading into map
The while loop I have while reading in from a file doesn't break. I'm not sure what the problem is. If you need any more information just ask. Code: #include <string> #include <map> #include <fstream> #include <iostream> #include <iterator> using namespace std; class Customer { public: string name; string address; Customer() {} }; class Purchase { public: string product_name; double unit_price; int count; Purchase() {} Purchase(string pn, double up, int c) :product_name(pn), unit_price(up), count(c) {} }; // Function Object for comparison in map container struct Cmp_name { bool operator()(const Customer& first, const Customer& second) { return first.name < second.name; } }; // ostream overloads ostream& operator<<(ostream& out, const Customer& c) { out << c.name << '\n' << c.address << '\n'; return out; } ostream& operator<<(ostream& out, const Purchase& p) { out << p.product_name << '\n' << p.unit_price << '\n' << p.count << '\n'; return out; } istream& operator>>(istream& in, Customer& c) { getline(in, c.name); getline(in, c.address); return in; } istream& operator>>(istream& in, Purchase& p) { getline(in, p.product_name); in >> p.unit_price >> p.count; return in; } int main() { cout << "Enter file to read orders from: \n"; string file; cin >> file; ifstream is(file.c_str()); if (!is) cerr << "File doesn't exist.\n"; multimap<Customer, Purchase, Cmp_name> orders; while (!is.eof()) { Customer c; Purchase p; is >> c; is >> p; orders.insert(make_pair(c,p)); } for (multimap<Customer, Purchase, Cmp_name>::iterator it = orders.begin(); it!=orders.end(); ++it) cout << it->first << it->second << "\n\n"; }
As for your Customer/Purchase ostream inserters, declare the second argument const& instead of non-const &. For example: ostream& operator<<(ostream& out, Customer const& c) That's necessary because the key in a map is immutable even if you're using a non-const iterator (modifying the key would invalidate whatever tree-sorting or hashing the map implementation uses. It's best to check every istream extraction operation for success, and break out of the loop the first time one doesn't succeed. Your "is.eof()" isn't going to read any extra (e.g. whitespace) characters, so it may claim "!eof()" at the semantic end of file. Something like: for(;;) { Customer c; Purchase p; if (!getline(is, c.name)) break; if (!getline(is, c.address) break; if (!getline(is, p.product_name) break; if (!(is >> p.unit_price >> p.count)) break; orders.insert(make_pair(c,p)); } Since those all return the original istream, it's the same as having a "if (!is) break;" after every attempted input. You can also simplify things somewhat by defining extractors for Customer and Purchase, e.g. istream& operator>>(istream &i,Customer &c) A failure to read a Customer would let you break out (the istream will evaluate as false if an eof stops the read from succeeding). Obviously you can make some of the failed-input points "ok to eof" and give a specific error in all the other cases.
1,360,257
1,360,282
Should I attempt to fix an arguably poor design decision in a 3rd party library?
My project involves Qt plus and unnamed 3rd party physics simulation library. The way the physics library works is that physical bodies cannot create themsleves; the "world" must instantiate them so that they can be added to the world immediately. My project creates a wrapper around these physical bodies to add some extra functionality, but because it stores these physical bodies it can't be instantiated either. The first question is, does it make more sense to allow these bodies to stand on their own? The part that I find awkward is that I have to pass a reference to the world to the object so that it can be created, when, to me, it makes more sense to pass the object to the world. To fix this, I can delay the creation of the 3rd party body until it is added to my world wrapper. But that means my world wrapper becomes in charge of initializing the body correctly. It also means that I can't really access any of the properties of the object until it's added to the world anyway, because they all rely on the 3rd party body being initialized... unless I duplicate all that data and then pass it off to the library when it's added. Is it worth the effort, or should I just continue to pass a pointer to my world wrapper so that my body wrapper can be created? I mention Qt, because the way the Qt graphics framework works is that you can create QGraphicsItems whenever you want, and they'll stand on their own, but they just won't be visible until you add them to the scene. The analogy here is that GraphicsItem == Body, and Scene == World.
To be truely effective, a facade pattern (your wrapper) has to hide the underlying details of the implementation from the user of the facade. This does mean using data transfer objects to hold the data. Facades can be cumbersome to implement but they give you the ability to change out the underlying implementation without affecting the end user. sudo code: Rock rock = new Rock(100); //simple data container for now. PhysicsFacade f = new PhysicsFacade(); //internally creates world. f.DoSomething(rock); //internally rock's data used by world to create an equivalent object which is attached to the rock data container for future use.
1,360,673
1,362,307
Any valid reason for code duplication?
I'm currently reviewing a very old C++ project and see lots of code duplication there. For example, there is a class with 5 MFC message handlers each holding 10 identical lines of code. Or there is a 5-line snippet for a very specific string transformation every here and there. Reducing code duplication is not a problem in these cases at all. But I have a strange feeling that I might be misunderstanding something and that there was originally a reason for this duplication. What could be a valid reason for duplicating code?
When I first started programming, I wrote an app where I had a bunch of similar functionality which I wrapped up in a neat little 20-30 line function ... I was very proud of myself for writing such an elegant piece of code. Shortly after, the client changed the process in very specific cases, then again, then again, then again , and again, and again .... (many many more times) My elegant code turned into a very difficult, hackish, buggy, & high maintenance mess. A year later, when I was asked to do something very similar, I deliberately decided to ignore DRY. I put together the basic process, and generated all duplicate code. The duplicate code was documented and I saved the template used to generate the code. When the client asked for specific conditional change (like, if x == y^z + b then 1+2 == 3.42) it was a piece of cake. It was unbelievably easy to maintain & change. In retrospect, I probably could have solved many of these problems with function pointers and predicates, but using the knowledge I had at the time, I still believe in this specific case, this was the best decision.
1,360,880
1,360,916
Best way to explain declarative fallacy in C++?
How might one craft a good explanation of why the following code is not correct, in that the author is attempting to write C++ code declaratively rather than procedurally? const double NEWTONS_PER_POUND = 4.448; int main() { double pounds, newtons; pounds = newtons/NEWTONS_PER_POUND; /* pounds equals 'unassigned variable'/4.448 */ newtons = 10.0; cout << pounds << endl; /* a big number, not 10.0/4.448 */ return 0; } The author expected cout to display a proper calculation, but instead gets a "crazy number." I would explain this as "C++ is procedural, and therefore at the time of the declaration pounds = newtons/NEWTONS_PER_POUND; newtons has not been assigned a value. Any better suggestions? Or an explanation why C++ isn't "smart" enough to carry out the behavior the user mistakenly expected?
Tell the author that pounds = newtons/NEWTONS_PER_POUND; commands the CPU to take the value at the address referred to as "newtons" take the value at the address referred to as "NEWTONS_PER_POUND" divide them store the result at the address referred to as "pounds" what he is looking for is most probably a function in imperative terms: double newtons_to_pounds(double newtons) { return newtons/NEWTONS_PER_POUND; } ... newtons = 10.0; cout << newtons_to_pounds(newtons) << endl; /* a big number, not 10.0/4.448 */ return 0;
1,360,974
1,367,004
ImpersonateLoggedOnUser and starting a new process that uses ocx fails
I write a c++ windows application (A), that uses LogonUser, LoadUserProfile and ImpersonateLoggedOnUser to gain the rights of another user (Y). Meaning the A starts using the user that is logged on on the workstation (X). If the user wants to elevate his rights he can just press a button and logon as another user without having to log himself out of windows and back in. The situation now is (according to the return values of the functions): LogonUser works, LoadUserProfile works and ImpersonateLoggedOnUser works as well. After the impersonation I start another process. This process is an application (B) that needs an OCX control. This fails and the application tells me that the .oxc file is not properly installed. The thing is, if I start B directly as the user that is logged on to the machine (X), it works. If I start B directly as the user (Y) to which I want to elevate my rights using A, it works. If I am logged in as (X) and choose "run as" (Y) in the explorer, it works! Do you know which steps I need to do to do the same as the "run as" dialog from windows?
Thank you all for your help. The following was able to solve the issue for me: I start the desired process using CreateProcessWithLogonW(). To get that function working properly I have to RevertToSelf() before I call it and do the impersonation again afterwards. So the sequence is now: LogonUser() LoadUserProfile() ImpersonateLoggedOnUser() // work with the app RevertToSelf() CreateProcessWithLogonW() // do the impersonation stuff again
1,361,028
1,361,575
stop python object going out of scope in c++
Is there a way to transfer a new class instance (python class that inherits c++ class) into c++ with out having to hold on to the object return and just treat it as a c++ pointer. For example: C++ object pyInstance = GetLocalDict()["makeNewGamePlay"](); CGEPYGameMode* m_pGameMode = extract< CGEPYGameMode* >( pyInstance ); pyth: class Alpha(CGEPYGameMode): def someFunct(self): pass def makeNewGamePlay(): return Alpha() pyInstance is the python class instance and m_pGameMode is a pointer to the c++ baseclass of the same instance. However if i store the pointer and let the object go out of scope, the python object is cleaned up. Is there any way to only have the c++ pointer with out the object getting cleaned up? More info: python object to native c++ pointer
You must increment the reference count of the pyInstance. That will prevent Python from deleting it. When you are ready to delete it, you can simply decrement the reference count and Python will clean it up for you.
1,361,071
1,361,074
What is the difference between .LIB and .OBJ files? (Visual Studio C++)
I know .OBJ is the result of compiling a unit of compilation and .LIB is a static library that can be created from several .OBJ, but this difference seems to be only in the number of units of compilation. Is there any other difference? Is it the same or different file format? I have come to this question when wondering if the same static variable defined in two (or more) .LIBs is merged or not during linking into the final executable. For .OBJs the variables are merged. But is it the same in .LIBs?
A .LIB file is a collection of .OBJ files concatenated together with an index. There should be no difference in how the linker treats either.
1,361,229
1,361,282
Using a static library in Qt Creator
I'm having a hell of a time finding documentation which clearly explains how to use a static library in Qt Creator. I've created and compiled my static library using Qt Creator (New=>Projects\C++ Library=>Set type to "Statically Linked Library"). It compiles and spits out a ".a file". The problem I encounter is when I try to use the library. I have another project that would like to use it (#include files in the library, etc) but I don't know the proper way to link with the library or include files from the library.
LIBS += -L[path to lib] -l[name of lib] Note! that filename of lib: lib[nameOfLib].a and you have to pass only original part -l[nameOfLib]
1,361,310
1,361,345
Converting unmanaged C++ code to C#
Anyone with pointers to a tool/utility for converting unmanaged c++ to c#? I have tried the http://www.pinvoke.net/ site but I cant find reference to this API AddUsersToEncryptedFile on this question.
In general this is really hard, because C++ offer different features than C#: templates, friends, zero-terminated strings, unmanaged pointers, COM, etc., not to mention that parsing C++ is a bitch of a job. To do it, you need a full C++ parser with name and type resolution, a set of ideas about how to convert each construction (problematic or not) into equivalent C# code, a means to encode those ideas into automated translation steps, and a plan for what to do with those parts of the code that don't translate well (typically, "fix by hand"). Using the DMS Software Reengineering Toolkit, which provides all the requisite machinery, my company, Semantic Designs, actually constructed such a tool, but never used it, for a large customer that wanted to move 800K SLOC of C++ into C#. About 2/3 of the way through the project, the customer had some birdcage management reshuffle, and the new managers decided not to proceed to save money (the tool itself was doing fine).
1,361,432
1,361,443
Compliation Error of a C++ second life library
I am trying to compile a slight part of second life library. Specifically, it is the llcommon part. I compiled it in Windows System with VS9. I failed and the compiler said it cannot recognize '_Ios_Openmode' as a member of 'std' The corresponding code is as following: explicit llifstream(const std::string& _Filename, std::_Ios_Openmode _Mode = in) : std::ifstream(_Filename.c_str(), _Mode) { } Can anyone help me figure out what the problem is, should I change my compiler configuration or something else?
I think it's meant to be std::ios::openmode.
1,361,618
1,361,837
Const Overloading: Public-Private Lookup in C++ Class
The following code does not compile, saying " error C2248: 'A::getMe' : cannot access private member declared in class 'A'". Why? I am trying to call the public interface. class B { }; class A { public: const B& getMe() const; private: B& getMe(); }; int main() { A a; const B& b = a.getMe(); return 0; }
Part of the problem which wasn't mentioned in other answers is that accessibility and visibility are independent concepts in C++. The B& A::getMe() private member is visible in main even if it isn't accessible. So in your call a.getMe() there are two overloaded members to consider, B& A::getMe() and B const& A::getMe() const. As a is not const it is the private member which is selected. Then you get an error because it isn't accessible. If you hadn't the private non const member function, you would have the const member as the only possibility and it would have be called as a const member can be called on non const object. Note that if visibility was conditioned to accessibility, you could have other kind of confusing behavior: you refactor a member, putting a call to a private member outside the class. Now, the private member is no more accessible and so the call is to a different member which is public. That silent change of behavior can lead to bugs hard to track. In conclusion: whatever are the rule of your language, never overload with different accessibility, it leads to confusion.
1,361,965
1,362,005
Compile simple string
Was just wondering if there are any built in functions in c++ OR c# that lets you use the compiler at runtime? Like for example if i want to translate: !print "hello world"; into: MessageBox.Show("hello world"); and then generate an exe which will then be able to display the above message? I've seen sample project around the web few years ago that did this but can't find it anymore.
It is possible using C#. Have a look at this Sample Project from the CodeProject. Code Extract private Assembly BuildAssembly(string code) { Microsoft.CSharp.CSharpCodeProvider provider = new CSharpCodeProvider(); ICodeCompiler compiler = provider.CreateCompiler(); CompilerParameters compilerparams = new CompilerParameters(); compilerparams.GenerateExecutable = false; compilerparams.GenerateInMemory = true; CompilerResults results = compiler.CompileAssemblyFromSource(compilerparams, code); if (results.Errors.HasErrors) { StringBuilder errors = new StringBuilder("Compiler Errors :\r\n"); foreach (CompilerError error in results.Errors ) { errors.AppendFormat("Line {0},{1}\t: {2}\n", error.Line, error.Column, error.ErrorText); } throw new Exception(errors.ToString()); } else { return results.CompiledAssembly; } } public object ExecuteCode(string code, string namespacename, string classname, string functionname, bool isstatic, params object[] args) { object returnval = null; Assembly asm = BuildAssembly(code); object instance = null; Type type = null; if (isstatic) { type = asm.GetType(namespacename + "." + classname); } else { instance = asm.CreateInstance(namespacename + "." + classname); type = instance.GetType(); } MethodInfo method = type.GetMethod(functionname); returnval = method.Invoke(instance, args); return returnval; }
1,362,063
1,362,151
naming convention of temp local variables
What is the standard way to name a temp variable in the local function? let me give you an illustration of what I am doing. I get a pointer to a structure, so I want store one of its members locally to avoid a de-referenced, and then any modification assign back to the pointer. To be more concrete: struct Foo { double m_d; }; void function (Foo* f) { double tmp=f->m_d; /***Other stuff***/ f->m_d=tmp; } I don't like tmp. If I have many of them in a function, they only add a confusion. Thanks
Linus Torvalds - Linux Kernel coding style from Linus Torvalds : LOCAL variable names should be short, and to the point. If you have some random integer loop counter, it should probably be called "i". Calling it "loop_counter" is non-productive, if there is no chance of it being mis-understood. Similarly, "tmp" can be just about any type of variable that is used to hold a temporary value. If you are afraid to mix up your local variable names, you have another problem, which is called the function-growth-hormone-imbalance syndrome.
1,362,154
1,362,183
Registering class instances for to be controlled by a class's function
Hehe I'm having hard time on choosing the question title. But let me explain about my problem to make it clearer. I'm now writing my own GUI library for my game in C++ with a DirectX wrapper out there. But I got no idea on how to render my in-game windows by just calling the "manager" class's draw function. For example, say I have a "manager" and "window" class already. the manager: class MyGUIManager { private: std::vector<MyGUIWindow> WindowCollector; public: MyGUIManager() { } virtual MyGUIWindow *NewWindow(char *szWindowTitle) { MyGUIWindow *temp = new MyGUIWindow(); temp->SetWindowTitle(szWindowTitle); return temp; } void RegisterWindow(MyGUIWindow targetWindow) // hopely this { this->WindowCollector.push_back(targetWindow); } void Draw() { // I wanted this function to be able to call all MyGUIWindow instances' Draw() function // can it be helped like this? for(int i = 0; i < this->WindowCollector.size(); i++) this->WindowCollector.at(i)->Draw(); // but the vector members must be referenced to each window instance.. } }; the window: class MyGUIWindow { public: MyGUIWindow() { this->SetWindowTitle("New Window"); } void SetWindowTitle(char *szWindowTitle); void Draw(); }; and the main program: //... MyGUIManager *GUIMAN = new MyGUIManager(); MyGUIWindow *FirstWindow = GUIMAN->NewWindow("Hello World"); MyGUIWindow *SecondWindow = GUIMAN->NewWindow("Hello World!!!"); GUIMAN->RegisterWindow(FirstWindow); // ?? GUIMAN->RegisterWindow(SecondWindow); while(Drawing()) { GUIMAN->Draw(); // I wanted this function to be able to call ALL MyGUIWindow instances' Draw() function //... } so the main question is, how to make all of MyGUIWindow variables can be controlled through WindowCollector vector?
Yes basically that will work, why don't you just try it out? But I would prefer using iterators instead of your loop, and also some kind of auto-pointer instead of just new (current example will probably cause a memory leak). Actually, begin by Googling std::vector... And passing arguments as references.
1,362,328
1,362,366
What is the mechanism through which destructors are called for stack-assigned objects?
How does C++ ensure that destructors are called for stack assigned objects? What happens to the destructor function (or a pointer to it) when I assign dynamic memory as follows: class MyClass { public: ~MyClass() { std::cout<<"Destructor called."<<std::endl; } MyClass() { std::cout<<"Constructor called."<<std::endl; } }; .................................................................... //Limit scope for example { MyClass instance; } The constructor and destructor are both called. What's going on here?
The compiler inserts a call to the destructor for the object at an appropriate position.
1,362,674
1,650,158
Problem synchronizing QThreads
Apart from main thread, I've ThinkerThread object _thinker whose finished() signal is connected to main thread's slot: connect(&_thinker, SIGNAL(finished()), this, SLOT(autoMove())); The slot autoMove() causes _thinker to initialize and run again: _thinker.setState(/* set internal variables to run properly */); _thinker.start(); This way _thinker can continue to run with new data and give some feedback to user in the main thread with autoMove() slot. The problem is when user wishes to load a new state for _thinker (may be from file or some other menu action), I cannot synchronous two states of _thinker. Suppose that _thinker is running, and user loads a new state from a file. Now, when _thinker finished(), it will call autoMove() and show feedback. But it is possible that wrong feedback is given to the user, because, may be loading from file causes internal state to be changed. That means, _thinker's internal state and main thread's internal states are not same. _thinker starts, with states say, s0. User loads another state from file, say s1. _thinker finished and autoMove() executes. So after step 3, autoMove() will give feedback for state s0, which is not expected. What I want to do is to stop execution of _thinker when user loads new state from file. I think my design is poor and I want to know the best practice in this case. My load function initializes _thinker in the same way autoMove() does, calling the same function (there is another function that calles _thinker.setState() and start()). Right now I've done the following in load() function: disconnect(&_thinker, SIGNAL(finished()), this, SLOT(autoMove())); _thinker.terminate(); _thinker.wait(); connect(&_thinker, SIGNAL(finished()), this, SLOT(autoMove())); This does not eliminate the problem completely, that is, autoMove() is still called and gives previous state's feedback. I'm using Qt Creator 1.2.1 with Qt version 4.5.2 in Windows. Thanks for your time. Edit This is the usual execution step (when load() is not called): _thinker.setState(); _thinker.start(); //when _thinker finished() autoMove(); > _thinker.setState(); > _thinker.start(); When load() is called: _thinker.setState(); _thinker.start(); load(); > _thinker.setState(); > _thinker.start(); //when _thinker finished() autoMove(); // this is the feedback for previous or current state > _thinker.setState(); > _thinker.start(); Note, load() causes _thinker to restart. Now, where to put a boolean check so that autoMove() should ignore ONLY ONCE?
How about using an integer id to determine which state has been computed, to see if it's still valid when computation has finished?
1,362,689
1,426,385
reducing memory requirements for adjacency list
I'm using adjacency_list< vecS, vecS, bidirectionalS ... > extensively. I have so many graphs loaded at once that memory becomes an issue. I'm doing static program analysis and store the callgraph and flowgraphs of the disassembled binary in boost graphs. Thus I can have several ten thousand functions==flowgraphs and one gigantic callgraph. I'd really like to reduce memory usage for my graphs while still using the BGL. Since my graphs are static after loading and edge and vertex counts are known beforehand I see huge potential for optimization. For example, I'd like to allocate a single buffer for all vertices/edges of a single graph and let the graph just store indices into that buffer. more questions: 1) what's the memory overhead of using vertex and edge properties? I have quite a few of them. 2) is it possible to convince the BGL to use the shrink to fit idiom? As I understand it the adjacency lists use push_back to add edges. Is it possible to reduce memory usage by swapping the resulting vector with a copy of itself? Maybe by copying the whole graph? 3) Is it possible to use boost pool allocators with the BGL? As far as I can tell the BGL currently performs lots of small allocations - I'd really like to avoid that for space and runtime efficiency reasons. Did anyone already build a BGL version optimized for memory usage? Should I try using the existing graph structures and augment it with custom allocators or somesuch or is it more fruitful to write my own implementation and try to stay interface compatible with the BGL so I may continue to use it's algorithms? best regards, Sören
There is a little known graph type called "compressed sparse row" graph in the BGL. It seems to be quite new and is not linked from the index pages. It does however employ a beautiful little trick to get the graph representation as small as possible. http://www.boost.org/doc/libs/1_40_0/libs/graph/doc/compressed_sparse_row.html Using this for some of our graphs I have already been able to reduce total memory usage by 20% - so it is a very worthwhile optimization indeed. It also stores the vertex/edge properties in vectors thus giving the smallest possible overhead for those as well. Note that the version shipping with the latest boost 1.40 supports directional graphs only (as opposed to bi-directional). If you need to be able to efficiently iterate over a vertice's out-edges and in-edges (as I did) you need to check out the boost trunk from subversion. Jeremiah was very helpful in adding that feature on my request.
1,362,728
1,363,656
C Runtime Library Version Compatibility: updates require rebuilds?
How do you construct a library (static lib or a dll/so) so that it isn't sensitive to future updates to the system's C runtime librarires? At the end of July, Microsoft updated a bunch of libraries, including the C runtime libraries. Our app is written with a mix of MFC/C++/VB and some third party libraries, including some that are closed source. I've been busy recompiling all of the libraries we have source to, but I am wondering if it is really necessary? What will happen if we link in or load a library built against an earlier version of the C runtime? When recompiling this stuff, what compiler and linker settings must be the same between the main application and the supporting libraries? I've discovered that the runtime library setting needs to be the same (we use the multi-threaded version /MD and /MDd) but I'm worried about other settings. I've actually pulled all the settings out into Visual Studio property sheets and I'm using the same sheets for all our different projects, but this doesn't work for 3rd party libraries and I'm thinking it is overkill. I have noticed that the linker will spit out a warning about conflicting libraries, but it suggests to just ignore the default libraries. Is it safe to do so? It seems like a very ugly solution to the problem.
If you are loading the 3rd party libraries as DLLs, they may depend on different runtime versions than your executable as long as you are not handing over parameters of types, that depend on the runtime libs (like STL types) the 3rd party lib is able to load the version of the runtime, that it has been built with or is statically linked to the runtime So, you don't have to recompile the DLLs. If you are statically linking to the libs or if you are handing over types defined in the runtime DLLs, you may get some problems with symbols, that are already imported in your lib, so most likely you will have to recompile it.
1,363,147
1,363,214
Is a public constructor in an abstract class a codesmell?
Is a public constructor in an abstract class a codesmell? Making the constructor protected provides all of the access of which you could make any use. The only additional access that making it public would provide would be to allow instances of the class to be declared as variables in scopes that cannot access its protected members, but instances of abstract classes cannot be declared at all.
My opinion would be that the public constructor might be seen to be confusing, and as you say making it protected would be correct. I would say that a protected constructor correctly reinforces the impression that the only sensible use of an abstract class is to derive from it. In fact, you only need to declare a constructor in an abstract class if it needs to do something, eg. initialise its own private members. I would then expect there to be other protected member functions that are helpful to derived classes. EDIT: Since no-one has posted any code and @sbi asked for some in a comment to OP, I thought I would post some: class Base: { public: // The question is: should the ctor be public or protected? // protected: Base():i(0){} // ctor is necessary to initialise private member variable public: virtual ~Base(){} // dtor is virtual (but thats another story) // pure virtual method renders the whole class abstract virtual void setValue(void)=0; protected: int getValue(void){ return i;} private: int i; }; Base b1; // Illegal since Base is abstract, even if ctor is public Base& b2=makeBase(); //We can point to, or refer to a Base b2.setValue(); // We're not sure what this does, but we can call it. b2.getValue(); // Illegal since getValue is protected
1,363,217
1,363,359
Binary Reproducibility in Visual C++
Is there a way to force the same code to produce the same binary in Visual C++? Turn off the timestamp in the PE or force the timestamp in the PE to be some fixed value, in other words?
I suppose you could write a utility to open the PE, set the checksum to 0, set the timestamp to what you like, recompute the crc, then write it back out. It would be nice if there were an official way to ensure perfect binary reproducibility, though. For more information: http://msdn.microsoft.com/en-us/magazine/cc301805.aspx
1,363,411
1,363,457
What to learn first - C++/STL/QT or .NET/C# - if I have limited time while learning and working?
I am currently a CS student at a 4th year(of total 5). I`m studying and working. At work I use ASP.NET. So, while working and studying, I have not so much time to learn new languages and techniques. What do you suggest to learn first - C++/STL/QT or C#/LINQ/WPF? I mean, C++ and its libraries are stable and do not change as fast as .NET technologies do. So, if I choose to learn C++ first, it might be that by the time I decide to finish my learning of it, .NET technologies are so far away that I can not actually catch them. And finally, at the end of June I received 6 books on WPF, WF, Astoria, EF and LINQ from Amazon. So, if C++ goes first, these books will become dated when I decide to switch on them. EDIT It seems to me that I will do .NET development for living and C++ for myself. But, nonetheless, I want to learn BOTH these directions. This is the tricky part - I am learning .NET/C# for almost a year, and C++ a little bit longer. So, the question is what is the best order to learn these things?
C++ is the cadillac of tools. Harder to learn and use but more powerful. C# does a lot of hand holding and is easier to learn but more limiting. Do you want to be the best of the best? Choose C++. Do you just want a job? Choose C#
1,363,665
1,363,687
Visual C++ math.h bug
I was debugging my project and could not find a bug. Finally I located it. Look at the code. You think everything is OK, and result will be "OK! OK! OK!", don't you? Now compile it with VC (i've tried vs2005 and vs2008). #include <math.h> #include <stdio.h> int main () { for ( double x = 90100.0; x<90120.0; x+=1 ) { if ( cos(x) == cos(x) ) printf ("x==%f OK!\n", x); else printf ("x==%f FAIL!\n", x); } getchar(); return 0; } The magic double constant is 90112.0. When x < 90112.0 everything is OK, when x > 90112.0 -- Nope! You can change cos to sin. Any ideas? Dont forget that sin and cos are periodic.
Could be this: http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.18 I know it's hard to accept, but floating point arithmetic simply does not work like most people expect. Worse, some of the differences are dependent on the details of your particular computer's floating point hardware and/or the optimization settings you use on your particular compiler. You might not like that, but it's the way it is. The only way to "get it" is to set aside your assumptions about how things ought to behave and accept things as they actually do behave... (with emphasis on the word "often"; the behavior depends on your hardware, compiler, etc.): floating point calculations and comparisons are often performed by special hardware that often contain special registers, and those registers often have more bits than a double. That means that intermediate floating point computations often have more bits than sizeof(double), and when a floating point value is written to RAM, it often gets truncated, often losing some bits of precision... just remember this: floating point comparisons are tricky and subtle and fraught with danger. Be careful. The way floating point actually works is different from the way most programmers tend to think it ought to work. If you intend to use floating point, you need to learn how it actually works...
1,363,787
1,365,438
Is it safe to call CFRunLoopStop from another thread?
The Mac build of my (mainly POSIX) application spawns a child thread that calls CFRunLoopRun() to do an event loop (to get network configuration change events from MacOS). When it's time to pack things up and go away, the main thread calls CFRunLoopStop() on the child thread's run-loop, at which point CFRunLoopRun() returns in the child thread, the child thread exits, and the main thread (which was blocking waiting for the child thread to exit) can continue. This appears to work, but my question is: is this a safe/recommended way to do it? In particular, is calling CFRunLoopStop() from another thread liable to cause a race condition? Apple's documentation is silent on the subject, as far as I can tell. If calling CFRunLoopStop() from the main thread is not the solution, what is a good solution? I know I could have the child thread call CFRunLoopRunInMode() and wake up every so often to check a boolean or something, but I'd prefer not to have the child thread do any polling if I can avoid it.
In particular, is calling CFRunLoopStop() from another thread [safe]? Here's what Run Loop Management says: The functions in Core Foundation are generally thread-safe and can be called from any thread. So maybe CFRunLoopStop is safe. But I do worry about their use of the word “generally”. My rule is: If Apple doesn't say it's safe, you should assume it's not. To err on the safe side, you might consider creating a run loop source, adding that to your run loop, and signaling that source when it's time to end the thread. That same document includes an example of a custom run loop source.
1,363,990
1,364,004
Help with semi-complex C++ assignment
This is a really easy question I'm sure but I'd appreciate the help. :) Here's my variable in the .h file: map<int, map<int, map<int, CString>*>*> batch; Here's me trying to assign a value: ((*((*(batch[atoi(transnum)]))[1]))[atoi(*docnum)]) = page; I added some extra parentheses while trying to figure this out in order to make sure the derefs were being processed in the right order - unfortunately, it still doesn't work. My application just crashes when running this line. I have it wrapped in a try {} catch {}, but no exception appears to be thrown. I don't use C++ very often and am wondering whether someone can tell me what I'm doing incorrectly. Here's the relationship I'm trying to model: List of transaction numbers (integers), needs to be ordered by key. For each transaction number, I have two types of documents, Payments and Invoices (buckets represented by 0 and then 1 respectively in my data struct above) In each type bucket, there can be one or more documents, These documents need to be ordered by id (docid) Each docid links to a string that consists of a comma-delimited list of files on the file system for processing. If you think there's a better data structure to use, I'd be interested to hear it. EDIT: I know there are many better ways to do this. The scenario was that I was handed a heap of horrible MFC-riddled C++ code and told to have something done yesterday. It basically boiled down to getting the data structure in there, loading it up and then outputting it somewhere else. I was just trying to pound it out quickly when I asked this question. I appreciate the design suggestions though.
The way std::map works is that it will allocate a node you are trying to reference if it does not exist yet. That means unless you are allocating your submap(s) and inserting them into your supermap(s), you're going to be given pointers to memory you don't own. At that point when you try to write to that memory you will crash. Do the maps need to be heap allocated? If not you can change the type to: map<int, map<int, map<int, CString> > > batch; // don't forget the spaces and your call can be: batch[atoi(transnum)][1][atoi(*docnum)] = page;
1,364,112
1,364,189
sizeof on a class inheriting from a base class with a virtual function
For the following code fragment. /*This program demonstartes how a virtual table pointer * adds to a size of a class*/ class A{ }; class X{ public: void doNothing(){} private: char a; }; class Z:public X { public: void doNothing(){} private: char z; }; class Y{ public: virtual void doNothing(){} private: char a; }; class P:public Y { public: void doNothing(){} private: char pp[4]; }; int main(){ A a; X x; Y y; Z z; P p; std::cout << "Size of A:" << sizeof(a) << std::endl;// Prints out 1 std::cout << "Size of X:" << sizeof(x) << std::endl;//Prints out 1 std::cout << "Size of Y:" << sizeof(y) << std::endl;//Prints 8 std::cout << "Size of Z:" << sizeof(z) << std::endl; //Prints 8 or 12 depending upon wether 4 bytes worth of storrage is used by Z data member. std::cout << "Size of P:" << sizeof(p) << std::endl; std::cout << "Size of int:" << sizeof(int) << std::endl; std::cout << "Size of int*:" << sizeof(int*) << std::endl; std::cout << "Size of long*:" << sizeof(long*) << std::endl; std::cout << "Size of long:" << sizeof(long) << std::endl; return 0; } The behaviour I seem to notice is that whenever an empty class is instantiated or an empty class is inherited from byte boundaries are not considered(ie: an object of size 1 byte is allowed), in every other case object size seems to be determined by byte boundaries. Whats the reason for this? I ask since at this point I am guessing.
Here is Stroustrup's explanation of why size of an empty class cannot be zero. As to why it is 1 byte, as opposed to something that conforms to the alignment boundaries, I would guess this depends on the compiler.
1,364,144
1,364,190
Determine total number of bytes read by a process
I am currently working on a project where one of our goals is to reduce the total amount of data read from disk. Is there a way to determine the total number of bytes run by a process? I am working with on a C++ application built with Visual Studio 2005, running on Windows XP. Ideally, I would like some sort of monitor that can print results if I specify a process name. But, if there's some sort of API I can use in my own application, that would be good too. I know that this must be possible somehow, because I can display the total number of bytes read in the task manager as the process is running, I would like to be able to obtain this number for a process that has already finished.
You can use GetProcessIOCounters function. This returns total read operations, write operations, other, read bytes, write bytes, and other bytes. The process still needs to be alive for this to work - holding a handle to the process should be sufficient. Alternatively, your process could log this info on exit. If your goal is to reduce your disk I/O, I recommend you use the Windows Performance Toolkit. This will show you what files you are reading the most data from, which threads are reading the most data, and help give you a bit more of a system wide view as well, in case you are causing disk I/O elsewhere in the system.
1,364,165
1,364,277
linked list with no duplicates
I have the following code (correct for my simple tests) for a linked list for no duplicates, but I think it is a bit ugly. Could anyone recommend a cleaner way to handle the duplicate code? The current piece in question is: if( (val == cur->val) || (cur->next && (val == cur->next->val)) ) But I think that a better solution might exist (that I don't see) using a different use of comparison operators. Also, can someone give me a suggestion for a "useful" assert or to inside here. It is hard to tell when to assert, especially if you have an if statement doing it for you. struct Node { Node(int v):val(v),next(NULL){} int val; Node * next; }; void insert(Node ** ppHead, const int val) { if(ppHead == NULL) return; if(*ppHead == NULL || val < (*ppHead)->val) { Node * tmp = new Node(val); // new throws tmp->next = *ppHead; *ppHead = tmp; } else { Node * cur = *ppHead; while(cur->next && (val > cur->next->val)) cur = cur->next; if( (val == cur->val) || (cur->next && (val == cur->next->val)) ) return; Node * tmp = new Node(val); // new throws tmp->next = cur->next; cur->next = tmp; } return; } int _tmain(int argc, _TCHAR* argv[]) { Node * list = NULL; int x[] = { 5, 4, 6, 7, 1, 8, 1, 8, 7, 2, 3, 0, 1, 0, 4, 9, 9 }; int size = sizeof(x) / sizeof(x[0]); for(int i = 0; i < size; i++) insert(&list, x[i]); Node * cur = list; while(cur) { printf (" %d", cur->val); cur = cur->next; } printf("\n"); return 0; }
I would write this more like: void insert(Node ** ppHead, const int val) { if (ppHead == NULL) return; while (*ppHead && (*ppHead)->val < val) ppHead = &(*ppHead)->next; if (*ppHead && (*ppHead)->val == val) return; Node * tmp = new Node(val); // new throws tmp->next = *ppHead; *ppHead = tmp; }