question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
5,149,722
5,149,778
Get pixel color after alpha blend
I have a RGBA color like 255, 0, 0, 100 How can I get the RGB if it was put onto a white background? eg. this red would become lighter and be more like 255, 100, 100 And the same thing if it were put onto a black background. Does this make enough sense? Preferably c++
As an example to my comment: struct Color { int R; int G; int B; int A; }; Color Blend(Color c1, Color c2) { Color result; double a1 = c1.A / 255.0; double a2 = c2.A / 255.0; result.R = (int) (a1 * c1.R + a2 * (1 - a1) * c2.R); result.G = (int) (a1 * c1.G + a2 * (1 - a1) * c2.G); ...
5,149,880
5,151,392
Vector in a struct wont let me push_back
Hi i have a vector in a struct as follows for pthreads argument passing: struct thread_data{ vector< pair < Database, string> > list_databases; ... ... }; ...some more code... then in a later function when i do the following ( mydata is a thread_data passed into the function ) ( entry being a pair< Dat...
mydata->list_databases.push_back(entry);, as you've shown in your question, will fail because thread_data::list_databases is a vector<...>* rather than a vector<...>. I.e., it's a pointer-type rather than a class-type, just as the compiler error you're seeing indicates. mydata->list_databases->push_back(new_store);, as...
5,149,929
5,150,945
can't access the Amazon s3 data by query string authentication
My codes below is used to access the amazon s3 to get a .zip file . and my request url is like this: http://xxx.s3.amazonaws.com/Pack1A.zip?AWSAccessKeyId=AKIAIEMQY4BEQUOCUP7Q&Expires=1298945115&Signature=sxoXZ4y7osXjn IycQynGbE9%2Bb5E%3D Code Snippet: time_t rawtime; time(&rawtime); gHttpDownloader->SetRequestHead...
Ensure that all ACLs are set correctly. The example URL is using Query String Authentication but the code example shows setting the Authorization is being set. You only need to set one or the other. See the docs. There is also a AWS PHP SDK.
5,149,986
5,150,009
Declaring using statement after namespace declaration
I am writing a utility library which is made up of several "Packages". The classes in each package are contained in various namespaces. I have an idea as to how I can simplify the situation by automatically declaring using statements at the end of class declarations (see below), this will avoid having the programmer do...
There is no point in using namespaces if you are just going to add a using declaration for each and every name declared in the namespace. Let users of your header files decide how they want to use the headers. If someone wants to use a using declaration, let him do it in the .cpp file directly; this will make the code...
5,150,000
5,170,701
How to hook AllocMem(), FreeMem() etc... calls ? It can be by any kind of technique dll, executable, etc
I'm trying to hook the events related to memory allocation to create an external debugger that have no need of extra implementation on source code. To do this I need to hook theses calls, some one know how to do this ? Something like, http://www.itworld.com/UIR000929interposers but that runs on windows too. C/C++ imp...
New informations: I'm studying about memory allocation to create my on debugger. BUT, Now I really found the point. As I'm working on Delphi I was looking the FastMM unit to check how it works... What was my first idea to create my own external debugger? Hook the request for memory allocation from an application to win...
5,150,056
5,150,084
MFC dlg class link errors for MyClass::GetMessageMap() and MyClass::GetRuntimeClass (MSVC 2008)
I copied an existing header for a dlg box class (created with the dlg class wizard/mfc wizard). All seemed to go fine until I added the cpp file to the project. Now i get odd link errors for some mfc magic methods: error LNK2001: unresolved external symbol "public: virtual struct CRuntimeClass * __thiscall Dlg...
You used DECLARE_DYNAMIC but forgot IMPLEMENT_DYNAMIC.
5,150,127
5,150,138
Member functions of a templated class, that take a template type as argument
I have a node struct and stack class. When I put the definition for 'void Push(T data)' outside the class definition I get: error: 'template<class T> class Stack' used without template parameters But when I put it inside the class definition it works fine. Here is the code: template <class T> struct Node { Node(...
You need to use the template <class T> again (and then use that T again as the template parameter for the class): template <class T> void Stack<T>::Push(T data) { Node <T> * newNode; if(size==0) newNode = new Node <T> (data, NULL); else newNode = new Node <T> (data, p_last); size++;...
5,150,187
5,150,232
passing function pointer not working
I have 2 libraries. Library A is compiled in C. Library B is compiled in C++, but it is mostly C code. I need to call the following function in library A: foo* c_func(int64_t (*ptr_to_func)(void)); The first thing this function does is: if(!ptr_to_func) return NULL; The ptr_to_func needs to point to a function in ...
What you are doing appears to be correct, with the caveat that your function bar() should be declared within an extern "C" { section. c_func() is probably returning NULL for a different reason. Step through it in the debugger and see (set a breakpoint at the beginning of c_func()).
5,150,359
5,150,368
C++ Pointer Assignment (Point to a Vector)
This is my first post in any forum so please bear with me. I am writing a C++ program that utilizes a custom class 'Book' with member variables such as title, author and other variables that are stored in strings. Amongst these member variables is a vector for storing objects of type Review (which is another custom cla...
To assign a pointer to 'point to' an instance of an object use pointer = &vector_of_reviews. The & operator gets the address of something, and it's this that you want to assign to the pointer. *pointer = vector_of_reviews dereferences the pointer (obtains the actual object 'pointed to'). This would more than likely cr...
5,150,465
5,150,565
What will happen if the recursive function is defined as inline?
Possible Duplicate: Can a recursive function be inline? I think that recursive function defined as inline will not have any effect and won't be made inline at all. Because, the compiler doesn't know how many levels to replicate the code of inline function. Any thoughts?
I tried browsing related SO questions to find a clear existing answer for you, but alas… So, the keywoard inline (or a member function being implicitly inline by defined in the class definition) has two effects: It guarantees that the function can be defined in multiple translation units without violating the One Defi...
5,150,544
5,150,574
c++ cout strange behavior with a custom Stack class
I have a custom stack class. Most of the code can be seen here: Member functions of a templated class, that take a template type as argument I fill the stack like so: stack <int> Astack; Astack.Push(1); Astack.Push(2); Astack.Push(3); Astack.Push(4); Then I do this: cout << Astack.Pop() << Astack.Pop() << Astack.Pop...
The order of evaluation of the function calls is unspecified. Your first expression basically boils down to this: cout << a << b << c << d; Each of a, b, c, and d are calls to Astack.Pop(). The compiler can generate code that evaluates those calls in any order it chooses. You should avoid writing expressions that ...
5,150,550
5,150,977
Python maxes one core while c++ doesn't
I wrote a simple program(calculating the number of steps for the numbers 1-10^10 using the collatz conjecture)in both python and c++. They were nearly identical, and neither were written for multithreading. I ran the one in python and according to my system manager, one core went straight to 100% usage, the others stay...
Python is, in general, quite slow at raw number crunching. This is because it uses its full, general purpose object model for everything, including numbers. You can contrast this with Java and C++, which have "native types" which don't offer any of the niceties of a real class (methods, inheritance, data attributes, et...
5,150,696
5,151,325
curl callback function threading
I have done some googling but haven't found the answer to this as of yet. When you registrar a function with curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, function) is that function guaranteed to be completed before curl_easy_perform(curl) returns? Or is it possible that function is being ran in parallel and may still ...
While I don't have an empirical source file+line number to quote to support this, having used libcurl quite a number of times in various projects over the years, I can confidently say: yes, curl_easy_perform will block until the write function you supply is finished being invoked.
5,150,704
5,150,822
Include everything, Separate with "using"
I'm developing a C++ library. It got me thinking of the ways Java and C# handle including different components of the libraries. For example, Java uses "import" to allow use of classes from other packages, while C# simply uses "using" to import entire modules. My questions is, would it be a good idea to #include every...
You're confusing the purpose of #include statements in C++. They do not behave like import statements in Java or using statements in C#. #include does what it says; namely, loads and parses the entire indicated file as part of the current translation unit. The reason for the separate includes is to not have to spend co...
5,151,198
5,151,235
How to disable Warnings for includes folders?
I have to use some library, and have no power to change it or care about it, EveryTime i compile a HUGE number of warnings popup. Useless things like : warning C4350: behavior change: 'std::auto_ptr<_Ty>::auto_ptr(std::auto_ptr_ref<_Ty>) throw()' called instead of 'std::auto_ptr<_Ty>::auto_ptr(std::auto_ptr<_Ty> &)...
#pragma warning is one option, though it's probably only feasible if you use precompiled headers or have very few source files in your own project. #pragma warning (push) #pragma warning (disable : 4350) #include <third/party/headers/in/question.h> #pragma warning (pop)
5,151,397
5,151,562
Bug in Programming Interviews Exposed?
I could not find an errata for the 2nd edition of this book. My question concerns the if-statement in the following piece of code. void removeHead (Node ** head) { Node * temp; if (!(*head)) { temp = (*head)->next; delete *head; *head = temp; } } So I understand that the point of the if-statement is ...
The book is a little flawed in that it first claims that there are no problems with *head as an input, and then further develops to say you should really pass in **head, and then says you should check *head. You really need to check *head AND head. As for if (!(*head)), if *head is NULL, this would be if (!0) which wou...
5,151,622
5,152,252
Error in Listing File from Directory in C++
I am having a problem with my code. Whenever i run the program, the last file search would return a zero value where in it shouldn't. here is the code: #include <vector> #include <string> #include <windows.h> #include <stdio.h> #include <iostream> #include <conio.h> using namespace std; string GetPath(string path){ ...
Try this as a sanity check: #include <tchar.h> #include <stdexcept> #include <vector> #include <string> #include <iostream> #include <windows.h> #ifdef UNICODE typedef std::wstring tstring; static std::wostream& tcout = std::wcout; #else typedef std::string tstring; static std::ostream& tcout = std::cout; #endif std:...
5,151,683
5,151,719
Why enum instead of static bool?
Why is it considered better practice to use enum not static const bool in template metaprogramming? I've read that somewhere in Alexandrescu's book but cannot find it and really would like to know it.
The key reason is that a static bool is a variable after all and a enum is a type - hence in case of enum no variable is ever instantiated and it's thus guaranteed to be a compile-time evaluation. Also see this question for more details.
5,151,875
5,151,971
typeid doesn't return correct type
cout << typeid(int&).name(); This, in my opinion, should return int& as a type, not an int, but on GCC 4.5.1 and on VS2010 SP1 beta it returns int. Why is this?
This is how typeid is supposed to work. When you apply typeid to a type-id of a reference type, the type_info object refers to the referenced type. ISO/IEC 14882:2003, 5.2.8 / 4 [expr.typeid]: When typeid is applied to a type-id, the result refers to a type_info object representing the type of the type-id. If the type...
5,151,958
5,152,771
C++ - how to create a multimap with 4 variables and 4 keys
I want to create a class like below class enumClass { int msdnEnum; std::string msdnEnumString; int localEnum; std::string localEnumString; } std::set<enumClass_Objects> enums; // all msdnEnums are unique, same aplies to other three. enums.find(given_msdnEnum)->FourthVariable; enums.find(given_localE...
Here's a simple example using boost.multi_index: #include <string> #include <boost/multi_index_container.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index/member.hpp> struct enumClass { int msdnEnum; std::string msdnEnumString; int localEnum; std::string localEnumString; }; name...
5,152,107
5,152,128
Building a C/C++ project without using Makefiles
I have a project containing C/C++ files. I'd like to build it without using make. What are my options? I'd like cross platform solutions if possible.
I've used SCons and it is very good. SCons is an Open Source software construction tool—that is, a next-generation build tool. Think of SCons as an improved, cross-platform substitute for the classic Make utility with integrated functionality similar to autoconf/automake and compiler caches such as ccache. In short, S...
5,152,238
5,152,290
need help to avoid downcasting
i created an eventhandler system simplified described by following classes IEventType - containing string name and hashed int value of the name for fast search IEventData - data send along with a triggered event EventManager - containing a std::map of <int, boost::signals2< bool( boost::shared_ptr< IEventData > ) > (t...
Could you put a virtual method in the IEventData interface e.g. actionEvent() that is implemented in the derived classes to call whatever is required to action the event? It would restrict you a bit if the event needs to be actioned in several different ways though.
5,152,345
5,714,899
Breakpoints stopped working in Microsoft Visual C++
All of a sudden breakpoints in Visual C++ have stopped breaking. I'm building the project in Debug mode. During execution the breakpoints say put as red dots, not as hollow dots (which would mean that it won't break due to lack of some debugging information) but still it doesn't break. I'm using Microsoft Visual C++ 6....
It was problem with IE 8. It started breaking at breakpoints after I downgraded to IE 6. Cruel microsoft developers.
5,152,501
5,152,544
What happens if you declare a variable inside a macro?
Suppose I have a macro defined as this: #define FOO(x,y) \ do { int a,b; a = f(x); b = g(x); y = a+b; } while (0) When expanding the macro, does GCC "guarantee" any sort of uniqueness to a,b? I mean in the sense that if I use FOO in the following manner: int a = 1, b = 2; FOO(a,b); After, preprocessing thi...
Macros perform just string substitution. The semantic is low and the the compiler have a limited knowledge of the preprocessor (essentially #pragma which in fact is not a preprocessor keyword, and source line info). In your case a and b are not initialized local value. Behavior is unpredictible. Your expanded code is e...
5,152,609
8,210,067
Qt moveToThread() vs calling new thread when do we use each
When do we use each of this function calls in a threaded application. given two functions fun1() and fun2() defined in the same class dealing with read/write of data into buffers(queue operation). to achieve multi-threading to these. we would have to run the two functions in a separate thread. now lets say the first fu...
Using moveToThread we can change the thread affinity of an object. What the OP asks is how we can run two functions of the same class in different threads. Let class A and two functions f1 and f2 class A { public: void f1(); void f2(int i); void run(); // shows how we can trigger f1 and f2 in different th...
5,152,633
5,153,633
Problem when converting from decimal to binary and returning a bitset
I have a strange problem. I have created a simple function to convert from decimal to binary. The argument is a int value that represents the number in decimal, and the function returns a bitset that represent the binary number. The problem is that conversion for a binary number smaller than 100000000000000000000000000...
You should use a long int, an array of long int or even a string as input to your method (depending on the source of your data and how you will call your function).
5,152,714
5,152,828
boost_logging fails to compile, because of 'CRITICAL_SECTION' : ambiguous symbol
I am using boost_logging for my project. In one of my file I just use my logging facility: LDBG_ << "something" but it does not seam to compile, I have the following error: 1>c:\boost\boost_logging\boost\logging\detail\ts\ts_win32.hpp(57) : error C2872: 'CRITICAL_SECTION' : ambiguous symbol 1> could be 'c:...
Try including boost logging headers before windows headers.
5,153,102
5,153,159
illegal reference to non-static member
I am trying to refer to a cstring mycustompath from a different class from my current class. CString test = CBar::mycustompath + _T("executables\\IECapt"); But I got this error instead: error C2597: illegal reference to non-static member 'CBar::mycustompath' c:\work\b.cpp 14 How to fix this?
This means that mycustompath is a property of a specific CBar object and not a property of the CBar class. You'll need to instantiate a CBar class CBar* myBar = new CBar(); CString test = myBar->mycustompath + _T("executables\\IECapt"); or reference one you already have or, if mycustompath doesn't vary by CBar object,...
5,153,128
5,153,156
How to remove repetitive characters from std::string
I have got a std::string like this: std::string fileName; where fileName is like /tmp/fs////js//config.js It is coming from somewhere and I need to store it. But when I store it, I need to remove extra '/' chars from the path, basically need only one separator between directory names and file names. I can remove these...
You're not going to find anything more efficient than that - think about it - you need to remove consecutive duplicated characters - the imnplication is that, even in the best case, you're going to have to look at every character at least once.
5,153,148
5,153,186
how to use std::function to point to a function template
#include <functional> int func(int x, int y) { return x+y; } int main() { typedef std::function<int(int, int)> Funcp; Funcp funcp = func; return 0; } But is it possible to point to a template function? #include <functional> template<class T> T func(T x, T y) { return x+y; } int main() { ty...
No. A template function is exactly that, a template. It's not a real function. You can point a std::function to a specific instantiation of the template function, e.g. func<int,int>
5,153,189
5,153,208
C++ Initialization lists - I don't get it
In Effective C++, it is said that data elements in the initialization list need to be listed in the order of their declaration. It is further said that the reasoning for this is that destructors for data elements get called in the reverse order of their constructors. But I just don't see how this could be a problem... ...
Well consider the following: class Class { Class( int var ) : var1( var ), var2(var1 ) {} // allright //Class( int var ) : var2( var ), var1(var2 ) {} // var1 will be left uninitialized int var1; int var2; }; The second (commented out) constructor looks allright, but in fact only var2 will be initiali...
5,153,696
5,153,786
Accessing a base class member in derived class
I have a simple class as below class A { protected: int x; }; class B : public A { public: int y; void sety(int d) { y = d; } int gety() { return y; } }; int main() { B obj; obj.sety(10); cout << obj.gety(); getch(); } How can I set the value of t...
B is an A, so creating an instance of B is creating an instance of A. That being said, I'm not sure what your actual question is, so here's some code that will hopefully clarify things: class A { protected: int x; }; class B : public A { public: int y; int gety() const { return y; } void sety(int d) {...
5,153,816
5,164,634
Get points enclosed by a 3d polygon
I have a polygon that lies on a 3D plane. i want to get all points enclosed by this polygon.can anyone help me ? i can make a 3D scan line algorithm by replacing the scan lines by planes and get the intersection of planes with my polygon but i want a faster solution. Thanks in advance.
"yes it's a convex 3p polygon ,but it all its points lie in the same plane" In that case - just convert the polygon and all the test points into 2D local coordinates of the plane and use a 2D algorithm: 2D ray shooting: You can still use similar algorithm to my 3d suggestion - shoot 2D rays originating from your test ...
5,153,908
5,154,222
parsing a mmap()-ed file
What would be the best (fastest) way to parse through a mmap-ed file? It contains pairs of data (string int), but I cannot persume number of whitespaces/tabs/newlines between them.
Assuming you've mmaped the whole file in (rather than chunks - as that would make life awefully complicated), I'd do something like the following... // Effectively this wraps the mmaped block std::istringstream str; str.rdbuf()->pubsetbuf(<pointer to start of mmaped block>, <size of mmaped block>); std::string sv; std...
5,153,971
5,154,084
How can I turn a big chunk of native code into a scalable service?
Greetings, I have a large piece of software developed in Eiffel. It is possible to use this code from C++, but it loads Eiffel runtime, and I can't trust the Eiffel code and runtime to be thread safe, when accessed by multiple threads from C++ I need to turn this native code into a service, but I would like to scale t...
If you're not tied to Apache but any other framework would suffice, I suggest you check out the ZeroMQ message passing framework. Its ZMQ_PUSH/ZMQ_PULL model with zmq_tcp transport seems to do what you want. Your setup would be something like: one "master" process servicing outside requests (in any language/platform, p...
5,154,116
5,154,143
std::function to member function
#include <functional> struct A { int func(int x, int y) { return x+y; } }; int main() { typedef std::function<int(int, int) > Funcp; A a; //Funcp func = std:::bind(&A::func, &a); Funcp func = std::bind(&A::func, a, std::placeholders::_1); return 0; } I am getting errors in ...
Funcp func = std::bind(&A::func, &a, std::placeholders::_1, std::placeholders::_2);
5,154,319
5,154,629
How do I prevent a non-Unicode application to convert charset of resources when loading them on a differently localized machine?
We have a non-Unicode, C++ application, written with Visual Studio, that has been originally written for machines using the codepage 1252 character set. Our application performs many post-processing steps on the contents of the resources after reading them, including looking up for resource strings in some files. Now p...
For LoadString, the obvious thing to do would be to call the Win32 API function LoadStringW() directly, which will give you the Unicode string directly. It might even work if you use the CStringW form of CString, like this (not tested!) CStringW str; str.LoadString(...); The menu and window functions will give more pr...
5,154,819
5,155,659
Are rvalues always constant?
When int i = 5; int j = i; Will rvalue i in this expression be a constant when evaluating the result? I'm asking this question because in my copy constructor its argument requires a const
There is a common misunderstanding around the lvalue/rvalue terms. They do not refer to variables, but rather to expressions. An expression can yield either an lvalue or an rvalue, and that can be either const or non-const. In particular, in your code the expression i on the right hand side of the definition int j = i...
5,155,069
5,155,265
Width of listview columns not respected
I have a listview where I add several columns: LVCOLUMN column; column.mask = LVCF_FMT | LVCF_TEXT | LVCF_WIDTH | LVCF_SUBITEM | LVCF_IDEALWIDTH; column.fmt = LVCFMT_LEFT; for(size_t i = 0; i < columns.size(); ++i) { const string columnName = Format("{0}. {1} ({2})", i + 1, columns[i].Name.empty() ? "?" : columns...
Vista and up has auto-sizing for columns for version 6. Its exact behavior isn't documented well. Either drop LVCF_IDEALWIDTH or use LVCF_MINWIDTH and set the cxMin member.
5,155,180
5,155,224
Changing a C# delegate's calling convention to CDECL
I have had this problem with C# when I was using DotNet1.1 The problem is this. I have an unmanaged dll, which has a function which takes a function pointer (among other arguments). When I declare the DLLImport in C# code, I pass a delegate. But the delegates in C# have stdcall calling convention whereas the unmanaged ...
By default the p/invoke system wraps your delegate in a stdcall function. You can change the generated wrapper's calling convention by using the UnmanagedFunctionPointer attribute: [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void MyDelegate();
5,155,420
5,162,306
I need a GUI for my project in c++
I need a GUI system that contain: a tree list that each item of list linked to a view and when I click on a Item open the view for next step I want to insert to each view some grids. I see a demo example named :dockpanelsuite http://sourceforge.net/projects/dockpanelsuite/ there is a explorer and multi document I thin...
Qt is better than MFC for a number of reasons including: . > 1.It is open source 2.It is cross platform. It works on Linux, some mobile devices and Mac OSX. This makes it easier to port programs to other platforms. > 3.Qt is much easier to use and learn that MFC. > 4.Above all Qt is well documented.
5,155,537
5,155,626
how to call .exe file within c++ program?
I want to use a exe file (convert.exe), inside my C++ program. This "exe" file change my output file format to another format. when, i use this convert.exe from my command-prompt (cmd), i have to type like this; convert -in myfile -out convertedfile -n -e -h where; myfile= name of the file, I obtain from my c++ ...
The std::system function expects a const char *, so how about you try system("convert -in myfile -out convertedfile -n -e -h") Then, if you want to be a little more flexible, you use std::sprintf can create a string with the right elements in it and then pass it to the system() function like so: // create a string, i....
5,155,708
5,155,861
gethostname on a machine with multiple network interfaces
What will the gethostname system call return on a machine with multiple network interfaces? Is it possible to configure this at the OS level?
The number of network interfaces used to connect the machine to the world is more or less independent of the number of host names. You can have multiple interfaces with a single name (even though it's somewhat unusual) or multiple names with a single interface (considerably more common). As to what value it does return...
5,155,820
5,155,876
Portably safe to pass NULL/zero to dynamic_cast?
Out of habit for checking null pointers, I have sometimes written: MyClass * c = someBasePtr ? dynamic_cast<MyClass*>(someBasePtr) : 0; if (c) {... In effect, checking for a null pointer before passing to dynamic cast, and also checking the return. I then read in the MSDN documentation A null pointer value is conver...
§5.2.7/4: If the value of v is a null pointer value in the pointer case, the result is the null pointer value of type R. So you don't have to check for a null pointer yourself. Same goes for operator delete, deleting a null pointer has no effect.
5,155,914
5,155,977
How to remove a record from a file?
I want to remove some information from a text file without shifting its all records. For example a text file customers.txt is given. it have a lot of records seperated by # delimiter. and each record contains fields separated by ;. Like this: 1665;John;Smith given a customer id, I want to remove a customer with corresp...
You have a couple of choices. 1) rewrite the remainder of the file past the record you are removing. 2) replace the record with some indicator that it is removed and handle that in your parsing of the file (like replacing the entry being removed with # or some other special character).
5,156,026
5,156,755
Windows message loops and WTL
I'm trying to understand the way WTL works, and message loops are confusing me right now. For example this code fragment: link The window is first created and after that the message pump is started. How come it works? Isn't the CreateEx, UpdateWindow and so on supposed to send their own invisible messages like WM_CREAT...
Understanding the difference between posting messages (PostMessage) and sending messages (SendMessage) is important here. Windows calls the window procedure directly for sent messages, they are not dispatched by the message loop. Which is how WM_CREATE and WM_SHOWWINDOW can be processed before the message loop is sta...
5,156,174
5,156,367
Return Double from Boost thread
Hi I have an Boost thread which should return a double. The function looks like this: void analyser::findup(const double startwl, const double max, double &myret){ this->data.begin(); for(int i = (int)data.size() ; i >= 0;i--){ if(this->data[i].lambda > startwl){ if(this->data[i].db >= (max-30)) { ...
tmp does not get the expected value after thread join because creating a boost::thread object copies all arguments to thread storage (see documentation). You must encapsulate tmp with boost::ref, which has the effect of providing a "copy-constructible reference" (sorry if the terminology is inadequate, but that's the i...
5,156,304
5,156,619
Specify norestart on msi installation executed through visual c++ app
I am using the MsiConfigureProduct function to install/uninstall an app that restarts after installation. I want the the install/uninstall to be silent and unattended but I cannot figure out how to make it norestart. To make the install/uninstall silent i used MsiSetInternalUI(INSTALLUILEVEL_NONE, 0); To achieve this...
You can use MsiConfigureProductEx and set the command line to REBOOT="ReallySuppress" http://msdn.microsoft.com/en-us/library/aa371101(VS.85).aspx
5,156,328
5,156,366
C++ 4 players in a array after element 3 reset to 0 with modulus
4 players in a array after element 3 reset to 0 with modulus. So if its players 3 turn it will reset to player 1 witch is element 0.
Use something like this: player = (player + 1) % 4;
5,156,381
5,158,877
Access Violation when dealing with large files that cannot be mapped to one view in Win32
Good morning, I am trying to write a cMemoryMappedFile class that deals with large files that cannot be mapped to one view in Win32. The code is at the pastebin url. In GetPointer(), we are trying to carefully map and unmap file regions as they are needed. We are encountering an access violation in GetPointer() on the ...
This calculation seems overly complicated. char * cMemoryMappedFile::GetPointer(int n){ unsigned int baseoff; if( n < MEM_BLOCK_SIZE / 2) { baseoff = 0; } else { baseoff = ((n + MEM_BLOCK_SIZE / 4) & (~(MEM_BLOCK_SIZE / 2 - 1))) - MEM_BLOCK_SIZE / 2; } ... As I...
5,156,427
5,156,556
How do you debug a Windows Service?
I read the MSDN article on the topic. To quote: Because a service must be run from within the context of the Services Control Manager rather than from within Visual Studio, debugging a service is not as straightforward as debugging other Visual Studio application types. To debug a service, you must start...
You could use a parameter to let your application decide whether to start as service or regular app (i.e. in this case show a Form or start the service): static void Main(string[] args) { if ((1 == args.Length) && ("-runAsApp" == args[0])) { Application.Run(new application_form()); } else { ...
5,156,538
5,156,563
C++ Passing Objects by Reference
I am trying to learn C++, and I am working through "Sams Teach Yourself C++ in 21 Days". I have been progressing quite well so far, and even got through the chapter on pointers without difficulty. However, a listing on "Passing Objects by Reference" has left me quite confused. There is a class with two constructors: cl...
SimpleCat(SimpleCat&) is a copy constructor. SimpleCat FunctionOne(SimpleCat theCat) uses pass by value semantics. This requires that the class instance be copied. Hence the call to the copy constructor.
5,156,597
5,156,707
Read data from a file individually and multiply the two columns in C++
I have a data file "1.dat" which has 4 columns and 250 rows. I need to read each row and process it such as to multiply two columns [col1 and col2]. Can you suggest a way to do this please? I have to use C++.
Assuming the file has delimited data, you will probably: use ifstream to open the file use std::getline( ifstream, line ) to read a line. You can do this in a loop. line should be of type std::string process each line using istringstream( line ) then reading these into your element. To store the read data you could u...
5,156,657
5,156,737
Is this a good use of a private constructor?
Trying to learn something new every day I'd be interested if the following is good or bad design. I'm implementing a class A that caches objects of itself in a static private member variable std::map<> cache. The user of A should only have access to pointers to elements in the map, because a full copy of A is expensive...
The implementation is intended to only allow you to create items via get_instance(). You should ideally make your copy-constructor and assignment operator private. It would not be thread-safe. You can use the following instead: const boost::once_flag BOOST_ONCE_INIT_CONST = BOOST_ONCE_INIT; struct AControl { boost:...
5,156,668
5,156,694
How do I pass a reference to an array, whose size is only known at run-time, as a function parameter?
I have an array that is being dynamically created based on user input, and I need to pass that array to a function where it will be manipulated and the results passed back out to the original array. When I try to use void MyFunction(int (&MyArray)[]) my compiler complains that it doesn't know how big the array is.
You can't. You could use a std::vector though.
5,156,675
5,157,038
how to use isatty() on cout, or can I assume that cout == file descriptor 1?
Well, the subject says it all, basically. I have a command-line utility that may be used interactively or in scripts, using pipes or i/o redirection. I am using cin and cout for i/o, and I want to write an extra EOL at the end if the output is console, so that user prompt will start from the next line. Within scripts t...
It is possible to use rdbuf() to change the destination of std::cin and std::cout inside your program. If you don't do that, it is probably quite safe to assume that cin = 0, cout=1 and clog and cerr both = 2 as the C++ standard states that they are synchronized with C stdin, stdout and stderr and those have per POSIX...
5,156,729
5,157,446
Ncurses static libraries to include with a C++ project
I have installed the latest ncurses library which my project is using. Now, I want to check in the ncurses static libraries into svn so that I can checkout the project on a different machine and compile it without having to install ncurses on the system again. So the question is what is the difference between libncurse...
libncurses.a - This is the C compatible library. libncurses++.a - This is the C++ compatible library. libncurses_g.a - This is the debug library. libncurses_p.a - This is the profiling library. If you want to find out if you can get by without using libncurses.a, you can rename the library and run a build of your ap...
5,156,794
5,157,122
How can I embed an unmanaged C++ form into a .NET application?
I have been able to successfully wrap my unmanaged Borland C++ dll, and launch it's forms from a C# .NET 4.0 application. Is it possible to embed a form from the dll directly into a .NET application? To clarify, the original form is being used as an embedded control in a Borland C++ project already. It essentially look...
Yes, you just need to use some low-level win32 functions from user32.dll : SetParent, GetWindowLog, SetWindowLong , MoveWindow . You can create an empty .NET container control, set the parent of the native window to the .NET control, then (optionally) modify the window style (i.e. to remove borders of native window), a...
5,156,797
5,156,911
Pros and Cons of Inversion of Control
Suppose I have a stream of [acme] objects that I want to expose via an API. I have two choices, callbacks and iterators. API #1: Callbacks // API #1 // This function takes a user-defined callback // and invokes it for each object in the stream. template<typename CallbackFunctor> void ProcessAcmeStream(CallbackFunctor...
One advantage of callbacks over iterators is that users of your API can't mess up iteration. It's easy to compare the wrong iterators, or use the wrong comparison operation or fail in some other way. The callback API prevents that. Canceling enumeration is easily done using a callback, BTW: Just let the callback retur...
5,156,963
5,157,004
Read multiple files to get data and process them in c++
Possible Duplicate: Read data from a file individually and multiply the two columns in C++ Hi all I have a sequence of data files[1.dat,2.dat,3.dat ........200.dat] each including 4 columns and 250 rows. I need to read each data and process them such as multiply the second column of each file. May you suggest me the...
You will have to read in the contents of every file into arrays. Next process the array content.
5,157,043
5,157,150
struggling with Object Oriented class design
I'm comming from an scientific background and I'm having trouble to think object oriented. I'm always thinking of functions not objects. For example I've got a Dataset containing multiple 2D arrays and I like to extract Regions of Interest out of these arrays. So my first Design was something like a RoIFinder class to ...
To me it sounds like in the specific situation you describe, this could be a fine OO design. OO in brief is about bundling together state behaviour (identity). Whenever you have data which represents the state of (a part of) the system, and you have behaviour tied to (typically manipulating) that data, you have a can...
5,157,169
21,670,542
Getting exception object address from catch (...) c++
I have a sample try/catch block. try { ... } catch (...) { ... } Is there any way to get exception object address or something from inside of catch(...) block?
You can kind of do this in C++11 by using std::current_exception() which returns "an exception_ptr object that points to the currently handled exception, or to a copy of it." However, as covered in other answers, since you have no idea what the type actually is, this is hardly useful. Note that very few operations are ...
5,157,206
5,157,452
Why does std::exception have extra constructors in VC++?
Something I noticed just now. Definition of exception in the standard (18.6.1): class exception { public : exception() throw(); exception(const exception &) throw(); exception& operator=(const exception&) throw(); virtual ~exception() throw(); virtual const char* what() const throw(); }; Definition...
Not really any good reason. The MS implementation has chosen to put the string handling in std::exception instead of in each class derived from it (<stdexcept>). As they actually also provide the interface required by the standard, this can be seen as a conforming extension. Programs following the standard works as exp...
5,157,274
5,157,359
How to make a function receive multidimentional array of arbitrary size in C++?
I was trying to make a function which takes a matrix as input and outputs some function of it in C++. But I want it to work on arbitrary size mxn matrix. i.e. I cannot specify in the arguments of the function the values of n (double matrix[][n]) . Because n will be arbitrary. Is there any way I can pass on an arbitrary...
template <typename T, size_t W, size_t H> void foo(T (&array)[W][H]) { // Do stuff with array here }
5,158,014
5,158,053
Why do different C++ compilers give different results for this code?
I'm writing some C++ codes for fun and practice, to learn more about language features. I want to know more about static variables and their behaviour in recursive functions. Trying this code in g++ compiler, I'm given expected result: #include <iostream> using namespace std; int f(const int& value) { static int r...
The order of evaluation of the following three subexpressions is unspecified: f(10) f(f(10)) f(f(f(10))) The compiler may evaluate those subexpressions in any order. You should not rely on a particular order of evaluation in your program, especially if you intend to compile using multiple compilers. This is because t...
5,158,117
5,158,147
C++ to create a Game for Nintendo DS
Well, I'm trying to do a small game for DS-DSi in C++. Just for fun and feel happy. I was wondering if there is any guide or I could get some help with getting started. I have no clue how it works or how to make it boot on the DS. Thanks~
I suggest getting a nds flash cart, like the cycloDS (for the DS) or an R4i (for the DSi). Thats how you can run your creations on the actual device. Here is a good list of tutorials starting from the beginning (setting up your environment, getting the armKit etc) on DS development. Tutorial: https://web.archive.org/we...
5,158,191
5,158,747
Choosing between Critical Sections, Mutex and Spin Locks
What are the factors to keep in mind while choosing between Critical Sections, Mutex and Spin Locks? All of them provide for synchronization but are there any specific guidelines on when to use what? EDIT: I did mean the windows platform as it has a notion of Critical Sections as a synchronization construct.
General points to consider: The performance cost of using the mechanism. The complexity introduced by using the mechanism. In any given situation 1 or 2 may be more important. E.g. If you using multi-threading to write a high performance algorithm by making use of many cores and need to guard some data for safe acces...
5,158,219
5,158,857
Find minimum of vector in Rcpp
Since last night I have been trying out Rcpp and inline, and so far I am really enjoying it. But I am kinda new to C in general and can only do basic stuff yet, and I am having a hard time finding help online on things like functions. Something I was working on was a function that finds the minimum of a vector in the g...
Glad you are finding Rcpp useful. The first comment by Billy is quite correct. There is overhead in the function lookup and there is overhead in the [] lookup for each element etc. Also, a much more common approach is to take a vector you have in R, pass it to a compiled function you create via inline and Rcpp, and ...
5,158,220
5,158,269
How to read a value of an hard coded address in C++?
I am looking to read the value that is located in address 302H. The purpose is to read an input from hardware (a part of a 104pc stack). When I run the following code a get this error: Unhandled exception at 0x004134b9 in setOutput.exe: 0xC0000005: Access violation reading location 0x00000302. #include <stdlib.h> #de...
In order to access physical memory directly under Windows, you need to develop a driver. I suggest you read up on Virtual Address Space to see why. The short story: The memory addresses you see from a usermode process has no relation to physical memory addresses, and the addresses where hardware lives are protected by ...
5,158,274
5,158,314
Netbeans errors on files that compile
I am new to qt, qmake, etc. I've created a .pri file that includes: INCLUDEPATH += $$QXMPP_INCLUDE_DIR \ /path/to/mysql-connector-c++-1.0.5/ LIBS += $$QXMPP_LIBS \ -lmysqlcppconn When I qmake -o Makefile make ./myProject or simply hit run in the Netbeans IDE my project compiles and runs success...
you have to define include directory in netbeans project properties. right click on project and go to properties there define include directory in c++ option.
5,158,578
5,158,682
Using std::accumulate
I always try to incorporate STL algorithms wherever I can, rather than writing manual loops. However, I'm having difficulty understanding how std::accumulate is generally useful. Whenever I need to calculate sums or averages, I almost always end up resorting to manual loops, because I have difficulty getting std::acc...
You're wrong about accumulate operator taking two of the same type. It does that only if you want to. The use the operator is specifically sum = op(sum, *iter). Thus your code: int count = std::accumulate(stuff.begin(), stuff.end(), 0, [](int current_sum, stuff_value_t const& value) { return current_sum + value.memb...
5,158,697
5,158,745
How to close IStream?
How can i close IStream in c++?
Check this reference. // read a file into memory #include <iostream> #include <fstream> using namespace std; int main () { int length; char * buffer; ifstream is; is.open ("test.txt", ios::binary ); // get length of file: is.seekg (0, ios::end); length = is.tellg(); is.seekg (0, ios::beg); // allo...
5,158,725
5,160,652
Qt Installation Problems on Mac OS X
Over the past 2 years I've had to install Qt 4.5, 4.6 and now 4.7 from source on Mac OS X. Each install causes me no end of trouble. My 2 main issues are: I build Qt in /tmp/ as instructed to. This directory gets wiped clean on a reboot, and stops me from being able to step through Qt code. I've got round this by buil...
I use Qt Creator instead of Xcode with Qt. So I can't help you on the Xcode project part. But I do have some success on building Qt with debug information. Unzip Qt source to some place that won't get wipe out like /qt. This is the steps I use to build it: cd /qt ./configure -prefix '.' -opensource -confirm-license -de...
5,158,764
5,158,818
C++: is it possible to search a vector/container for a particular string/value and return its index?
I would appreciate some advice related to manipulating data in vectors. I have written code that results in two sets of vectors: strings (labels/names) and doubles (data). The order of the labels in the string vector may be different for each calculation I do. Here's what I would like to do. Let's say that one elem...
Use std::find vector<string>::iterator it = std::find(vec.begin(), vec.end(), "Tom"); if (it == vec.end()) return -1; else return it - vec.begin(); A better solution would be to pick a more suitable container, such as the mentioned std::map
5,158,848
5,158,910
MPI_Recv - How to determine count?
So let's say I have an MPI program with 2 processes, rank 0 and rank 1. int i[20], j[20], temp, size; In process with rank 0, I have for(temp=0; temp<20; temp++) i[temp] = temp; MPI_Send(i, 15, MPI_INT, 1, 1, MPI_COMM_WORLD); and let's say process with rank 1 then does // At this point, size is declared, but...
Look at the documentation for MPI_Recv: Input Parameters count maximum number of elements in receive buffer (integer) So yes, you do need to pass in a value. Note that it need not be the actual number of elements you're receiving, but only the maximum number of elements that your buffer can hold. In your case, yo...
5,158,990
5,159,177
Concerning RAII: How to prevent errors caused by accidentally creating a temporary?
A while age a colleague told me he spent lot of time debugging a race condition. The culprit turned out to be something like this: void foo() { ScopedLock(this->mutex); // Oops, should have been a named object. // Edit: added the "this->" to fix compilation issue. // .... } In orde...
If you're going to define a macro, I'd probably rather define this one: #define GET_SCOPED_LOCK(name, mtx) ScopedLock name(mtx) and stop creating objects other than via the macro. Then rename ScopedLock to ThisClassNameShouldNotAppearInUserCode if that helps.
5,159,091
5,159,138
C++ map iterator problem
why is this code problematic(in visual studio 2010)? #include <iostream> #include <fstream> #include <string> #include <map> using namespace std; int main() { map<string,int> map; map<string,int>::iterator iter = map.begin(); } it just tells me there is a problem in the iterator definition(argument list for...
You called your variable map and you used using namespace std; which will result in name lookup issues as you are using a variable and a library container called the same thing. David in the comments and below explains that portion more. You can do several things (and there are more you can do beyond these): Qualify y...
5,159,353
5,159,395
How can I get rid of the __imp__ prefix in the linker in VC++?
I'm using libcurl and am getting the following sort of linker errors in VC++ 10. 1>main.obj : error LNK2019: unresolved external symbol __imp__curl_easy_strerror referenced in function "class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __cdecl curl_httpget(class std::basic_string<c...
The __imp__ prefix appears whenever you are linking to a DLL. It does not appear when linking to statically linked libraries. Most likely the code is generated to be linked against a DLL import lib, but you have linked it with a static lib instead. The prefix is added when you mark the imported function with __declspe...
5,159,417
5,159,576
C++ What to put in a Class Declaration and what not
I'm totally confused where to put e.g. the definition of a constructor. Sometimes you see something like this // point.h class Point { Point(int x, int y) { x_ = x; y_ = y; } private: const int x_; const int y_; } Then you sometimes see something like this: // point.h class Point { Point(int x, int y...
Contrary to some of the answers there are differences in these two practices. If you put the implementation into the class declaration the method will be automatically marked as inline. For very short methods like wrappers this is a advisable practice very useful feature. If you put the implementation into a separate ....
5,159,436
5,159,729
changing const values at develop-time without recompiling everything
Right now I have a considerable amount of would-be magic numbers stored in constants. These get tweaked a lot in between each build. eg const int numAPPLES = 25 right now these are each defined at the top of each associated class header. But sometimes they need to be shared and I and up having to either: Copy the def...
If you need the constants at compile time, you really have to recompile when they change. If you only need the values at runtime, you can declare them as extern const int numAPPLES; and put the actual values in a separate .cpp file. When you change a value, you just have to recompile that one file.
5,159,438
5,159,530
Strange compiler error when trying to create a temporary object
After I posting this question I tried to reproduce the problem of accidental rvalue creation when creating a scoped RAII object. Now it appears that I can't reproduce it without compiler errors! In the following code sample, in Test::foo() the second ScopedLock creation doesn't compile. The gcc compiler error seems tot...
You have two user declared constructors, so there is no compiler generated default one. Yes, Type (i); is handled in the same way as Type i; Such parenthesis are useful in more complex declarations such as Type (*i)(); to declare a pointer to a function returning a type.
5,159,516
5,159,548
How to Convert code to Obj-C?
How do I convert this to Objective-C?? Mainly this: float *newH= new float[newD]; What do I substitute new for in obj-c?? int newD = 100; float *newH = new float[newD]; for(int i=0; i<newD; i++){ newH[i] = 0.0f; }
Objective-C is a true superset of C. In C, one uses malloc to allocate memory. So, float *newH = malloc( newD * sizeof( float) ); Of course, depending on what you are really doing, you may also want to investigate NSArray and NSNumber. Note, that Objective-C++ is available as well and you can continue to use 'new' to ...
5,159,876
5,160,336
QObject::connect simply “rejects” my object at compile-time(!)
C is a QObject derived class, I can use it successfully. I get a compilation error on the “connect”. If i’d change “this->controller”, to “this”, on the target, it will work fine. Something about the this->controller as the recipient causes this not to compile. I realize it must be something stupid, but the cause evade...
MY bad. The class of "this->controller" was declared with a forward declaration only due to circular referencing of *.h files. That caused the problem. Not much the compiler could do with it.
5,159,901
5,160,380
How to use the same QAction in two QMenus with different text?
So I have an action I want to expose in multiple menus (one of the main menus, and some context menus). I'd like the menu item text to differ slightly from menu to menu (to make the mnemonic unique, and to be more or less verbose as necessary in each context). In MFC (which I have the pleasure of migrating away from at...
I don't know about MFC, but in Qt - QAction is just an interface. One QAction object can have only one text to display. But the real action QAction does, you will implement in what Qt calls SLOT. Then you can have as much interfaces(or QActions objects) pointing to the same slot - just connect all QAction objects, that...
5,159,960
5,161,211
Seg faults with pthreads_mutex
I am implementing a particle interaction simulator in pthreads,and I keep getting segmentation faults in my pthreads code. The fault occurs in the following loop, which each thread does in the end of each timestep in my thread_routine: for (int i = first; i < last; i++) { get_id(particles[i], box_id...
This is only an educated guess, but based on the problem going away if you use one lock for all the boxes: push_back has to allocate memory, which it does via the std::allocator template. I don't think allocator is guaranteed to be thread-safe and I don't think it's guaranteed to be partitioned, one for each vector, e...
5,160,053
5,160,086
Attaching to another process in C++
Is there a way to attach my process to another process? (for example, instead of opening the other process in with CREATE_PROCESS with some other flag?) just like a debugger can do... thanks :)
You're looking for DebugActiveProcess.
5,160,189
7,157,193
Threading: doing processing in background of C++ Cinder app to keep the UI responsive
I was happy to get my first C++ app working after a few hours of hacking this afternoon. The app trades the X-dimension for the time-dimension in a video. Example: http://www.flickr.com/photos/forresto/5489312991/ Source: https://gist.github.com/849779 Any suggestions for how to optimize the source would be welcome...
The answer seems be threading. It works like this with Cinder: void MyApp::setup() { thread(&MyApp::processFrame, this); } void MyApp::processFrame() { // TODO define mFrameTemp here // Copy to the texture which we'll actually render mFrame = mFrameTemp; } void MyApp::draw() { if (mFrame) gl::draw(mFrame,...
5,160,370
5,160,413
Removing Pocket PC pollution from VC++ project
I have a VC++ project in VS 2005 that I make 32 and 64bit releases of. I just installed VS 2010 and am trying to port the project to the newer Visual Studio. It won't port because the project references the platform "Pocket PC 2003 (ARMV4)". I have never created any project for Pocket PC. I don't know why this is de...
Open the project/solution files in a text editor and manually remove the references to it.
5,160,372
5,160,388
how do i provide an overload to take a vector argument?
how do i provide an overload to take a vector argument? void res(uint8_t* buffer, int len) { std::vector<uint8_t> buf( buffer, buffer + len ); // here i want to pass buf as uint8_t* to onther func pack((uint8_t*)buf, len));// error } IntelliSense: no suitable conversion function from "std::vector<uint8_t, std::allo...
Pass the address of the first element. pack(&buf[0], len);
5,160,535
5,160,982
Under Windows, how can you identify the current console user and then do a logoff against that user?
I need the ability in C++ code to logoff the console user when call from an administrator process or if it is called by that user and maybe a windows service in the future. The issue I am running into is that ExitWindowsEx will only logoff the user that calls it. If an administrator process calls a logoff the console u...
Use WTSGetActiveConsoleSessionId to identify the console session, but to go further you are going to need some permissions, you would have to call WTSQueryUserToken (You need to run as SYSTEM to do this) to get a token handle and then CreateProcessAsUser or impersonate and call ExitWindowsEx, or if you are not in a ser...
5,160,593
5,160,687
Shared libraries, object constructors and fork() behavior
g++ (Ubuntu 4.4.3-4ubuntu5) 4.4.3. Edited for clarity. I have a shared library in which I want to do something the first time it's loaded, and whenever there are no more references to it. I have tried two ways to do it, with the same result. The first was using the suggestion at this link. The second was by creating...
That is not "shared memory". You are only "sharing" the objects in a very attenuated sense -- fork() is making a copy of the parent's already-constructed object as part of copying the entire parent process. As an implementation detail in most operating systems, you get copy-on-write semantics (so the same physical bit ...
5,160,736
5,160,811
is there such a thing as a 64bit int in c++?
Is there a real platform/compiler combo that defines int as 64 bits? Or is this just used to scare new programmers like myself into using int32_t where size matters (e.g. saving to a file) in order to make it "portable"?
There absolutely are such systems. There may be more in the future (or there may not). And do you want to take a bet on what int will be on a possible 128-bit architecture? Wikipedia has an incomplete-but-useful rundown: http://en.wikipedia.org/wiki/64-bit#64-bit_data_models
5,160,924
5,161,107
Trouble with insertion function for ordered linked list class in C++
I have a template class OList that is an ordered linked list (elements are ordered in ascending order). It has a function called void insert(const T & val) that inserts an element into the correct place in the list. For example, If I had an OList of ints with the values { 1,3,5 } and called insert(4), the 4 would be in...
You are passing the pointer to pre by value into findInsertPoint, so it is copied, and the function changes the copy of pointer, and when the function returns, it is still the old pre, not the pre from inside the function. If you want to change the pointer, you must pass pointer to the pointer to the function (or refer...
5,161,389
5,161,485
Parser Help Program Not Working
--> ---> a | b ---> 1 | 1 It's suppose to start will a or b and 1 afterward. it doesn't matter how many 1's are after a or b. for example: a1, b1, b111111, a111 everything I type in is invalid but this is supposed to be valid: a1, b1, b111111, a111 /* <S> --> <A><B> <A> ---> a | b <B> ---> 1 | 1 <B> It suppos...
Look carefully at this line if(ToBeChecked = '\0') what does it do, and why might that not be what you want?
5,161,473
5,161,640
Question about smart pointers in C++
Is auto_ptr good to work with only for local variables? If I need to work with classes too, do i need copied pointer ?
The auto_ptr destructor does deallocate the memory, so you are correct. Once you leave the auto_ptr's scope the thing you're pointing to will go away. You might be looking for something like a shared_ptr, which is a reference counted smart pointer. It will be part of the next C++ standard. Boost has an implementati...
5,161,614
5,161,627
Is there an open source thread safe C++ object pool implementation?
I need to create a pool of socket connections which will be served to multiple worker threads. Is there a thread safe object pool implementation with functionality similar to Apache Commons' GenericObjectPool?
Check out boost.flyweight.
5,161,616
5,161,665
C++ Problem resolution - is it the best way to simulate a "tuple"?
I've got the following problem: "Write a template function vectorMAXMIN() that will accept a vector and a number indicating the size of the vector and will return the max and the min values of the vector"... So i think in it... Create a class vector to avoid the "size" passing value and control the insertions and can g...
I would use a std::pair to return the minimum and maximum values. Also, if you're doing this in C++, you might want to use the std::vector implementation instead of a homegrown one and "just" scan the passed-in std::vector once instead of implementing your own vector. Though, the way the question reads, you're probably...
5,161,761
5,162,042
Qt Blocking call to display dialog?
I am mucking about with Qt and QML. So I would like to have a blocking call to display a dialog and retrieve user input. The call is guaranteed not to be on the current UI thread. I have QDeclarativeView object that I have created using QML. I can display it using the show method(). But now I want to block until the us...
Use a Qt::BlockingQueuedConnection connected to the QDialog::exec() slot. http://doc.qt.io/qt-5/qt.html#ConnectionType-enum
5,162,620
5,165,758
OpenGL glMatrixMode help
I'm starting to work a little on OpenGL stuff, and I'm seeing a lot of examples that make calls to the glMatrixMode function. From what I've gathered, setting this to either GL_MODELVIEW or GL_PROJECTION (etc) will activate that specific transformation matrix and all subsequent calls to matrix transformation functions...
glMatrixMode doesn't "activate" matrices. The OpenGL fixed pipeline uses 3 matrices (sometimes 4): Two are responsible for transforming the geometry, one for transforming texture space (and some implementations one for color adjustments). Those matrices are used all the time. The modelview matrix is used to move geoemt...
5,162,684
5,162,711
Unexpected in macro formal parameter list Error
I'm an intern student and my boss told me to do porting from Linux c to Visual C++. When I built the coding, I found this error "unexpected in macro formal parameter list", here is the code #define cache_info(format, msg...) do { \ ;\ } while (0) I don't know what is wrong and what the coding is f...
Sounds like your version of Visual C++ doesn't support variadic macros. you might need to try something like this to get it to work. #define FUNC(foo) ThisFunc foo void ThisFunc(int, ...); int main() { FUNC((123, 456)); } or you could just be missing a comma?.... #define cache_info(format, msg,...)