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
4,115,562
4,115,609
correctly fixing conversion and loss of data warnings?
I have a class called PointF and it has a constructor that takes a Point, and I keep getting "possible loss of data warnings". How can I show that my intention is in fact to make a float value into an int, among other tings? I tried static_cast and (float) but they did not fix the warning. For example: int curPos = cei...
A cast should do the trick; that says "explicitly make this type into that type", which is generally pretty silly for a compiler to warn for: int curPos = static_cast<int>(ceil(float(newMouseY / font.getLineHeight()))); Or: outputChars[0] = static_cast<char>(uc); Make sure the casts you tried were akin to that. You s...
4,115,641
4,115,645
Fixng unused formal parameter warnings without making an abstract class
I have a base class and it has virtual functions. The issue is that, the base is allowed to be instanced, but that means that all of its functions need a definition. This causes the compiler to warn me about unused parameters. What can I do to properly get rid of these warnings without making pure virtual functions and...
Usual solution is: virtual void bar(int x) { (void)x; } or: virtual void bar(int) {} This prevents the compiler from whinging. Note that this technique isn't restricted to virtual member functions; it should work for any function where you don't intend to use one or more arguments. On an unrelated note; an instantia...
4,115,679
4,115,700
A loop and a character in int variable doesn't work as i expect
i saw an unusual problem in this code: #include <iostream> using namespace std; int main() { int number; bool repeat=true; while (repeat) { cout<<"\nEnter a number:"; cin>>number; cout<<"\nNumber is:" <<number; cout<<"\nRepeat?:"; cin>>repeat; } system("pause"); return 0; } here in this code when...
After reading in user input which cannot be converted, the input stream is in an invalid state. You need to empty the stream and call the clear method to reset the error bits on the stream in order to resume normal operation. If you detect that input was not successful (using the input streams state bits, accessible vi...
4,115,756
4,115,788
How does endianness affect enumeration values in C++?
How does endianness affect enumeration values in C++? Is the size of an enum dependent upon how many enumerations there are and thus some enums are 1 byte, while others are 2 or 4 bytes? How do I put an enumeration value into network byte order from host byte order?
Endianness affects enumerations no more or less than it does other integer types. The only guarantee on size is that it must be possible for an enum to hold values of int; the compiler is free to choose the actual size based on the defined members (disclaimer: this is certainly the case for C, not 100% sure for C++; I'...
4,115,819
4,117,178
Hiding a file from other programs
I need to make a file not appear to another program. For instance, when another program gets the list of files in a folder, I want one particular one not to show up. I am injecting a DLL from which my code will run into the process from which I want to hide the DLL file on the filesystem. I am using Microsoft Visual C+...
Yes, as you've mentioned you need to intercept the file/folder enumeration APIs and filter out the specific file/folder from the enumeration result in order to "hide" that file/folder. This can be done either at user mode or kernel mode. User mode: User mode hooking involves DLL injection. There are many places where y...
4,115,821
4,115,928
c++ lib viewer download
is there any lib viewer or converter to h files that i can download?
There are umpteen tools that let you inspect libraries, but very few that generate header files (a library file seldom contains enough information to do that). Example using Microsoft's toolchain: C:\Program Files\Microsoft SDKs\Windows\v7.0A\Lib> dumpbin /symbols AclUI.Lib Microsoft (R) COFF/PE Dumper Version 10.00.3...
4,116,261
4,116,343
OpenGL lighting question
I have got all my OpenGL lighting working properly, with the normals, materials, ect... My problem is the way in which OpenGL renders the faces when the light is behind the face. If the light is behind a face, it should render a black face, but instead it renders what the backface of the face would look like. How do I ...
The problem you are seeing occurs because both sides of the polygon use the same normals in their lighting calculations. The solution to this is to set: float modelTwoside[] = {GL_TRUE}; glLightModelfv(GL_LIGHT_MODEL_TWO_SIDE, modelTwoside); This causes OpenGL to reverse the normals before rendering the back side. Ope...
4,116,368
4,150,720
Compiling PHP Extension with correct API Version on Windows
I have finally created a very simple "Hello World" style PHP Extension dll on windows, after immeasurable hassle. However, although I have successfully created a DLL, and put it in the extensions folder, and told php.ini about it, now I get this: PHP Warning: PHP Startup: \x81\xc2\xc0\x03L&\xc0\x03: Unable to initial...
It turns out it was the "Data Alignment" - My DLL was being compiled using "Word" alignment and it needed to be double-word.
4,116,387
4,116,400
How can I increment a vector iterator?
I am learning how to work with vectors in my C++ college class. I have ran into an issue that has been keeping me from using iterators with vectors. This is my source code: template <class T> void HuffMan<T>::search_freq(T temp) { //checks for frequency if(objects.empty()){ objects.push_back(temp); return; ...
Your problem is that you're incrementing after calling push_back, which invalidates the iterator. This is a symptom of a bigger problem. I assume you want to test temp against every element in the vector and call push_back if there are no matches, but you're actually calling push_back for every element that's differen...
4,116,724
4,116,733
What's wrong with my multilined macros?
I have a function mainFunc which needs to call a several times another function process. A process has a lot of arguments but mainfunc in different calls change only two of them/ Instead of another it passes local variables which are defined and assigned before this calls to process. So I wrote a simple macro which sub...
The most likely cause is that there's extra whitespace after one of the backslashes in the macro definition. Make sure that \ really is the last character on a line. Oh, and your code will leak memory, since est1 is evaluated twice in your macro definition - it expands to process(pred1, new Est(...), ...) and then late...
4,117,002
17,721,201
Why can I access private variables in the copy constructor?
I have learned that I can never access a private variable, only with a get-function in the class. But then why can I access it in the copy constructor? Example: Field::Field(const Field& f) { pFirst = new T[f.capacity()]; pLast = pFirst + (f.pLast - f.pFirst); pEnd = pFirst + (f.pEnd - f.pFirst); std::copy(f....
IMHO, existing answers do a poor job explaining the "Why" of this - focusing too much on reiterating what behaviour's valid. "access modifiers work on class level, and not on object level." - yes, but why? The overarching concept here is that it's the programmer(s) designing, writing and maintaining a class who is(are...
4,117,072
4,117,080
prepending number with 0's
Possible Duplicate: Print leading zeros with C++ output operator (printf equivalent)? #include <iostream> #include <iomanip> int main() { int n = 16; std::cout << ???(5) << n << std::endl; } I want the output to be 00016 setw() prepends with spaces. Isn't it configurable what characters to prepend with setw()...
You also need setfill('0').
4,117,142
4,117,151
How can I stream hexadecimal numbers with A-F (rather than a-f)?
Is it possible to make ostream output hexadecimal numbers with characters A-F and not a-f? int x = 0xABC; std::cout << std::hex << x << std::endl; This outputs abc whereas I would prefer to see ABC.
Yes, you can use std::uppercase, which affects floating point and hexadecimal integer output: std::cout << std::hex << std::uppercase << x << std::endl; as in the following complete program: #include <iostream> #include <iomanip> int main (void) { int x = 314159; std::cout << std::hex << x << " " << std::uppe...
4,117,362
4,117,383
How can be done this automatic?
Is there any way to do this automatically for all derived classes, that i don't have to create function applyPack for all nested classes. This is piece of my code: /** every class has registered id with this function */ template<typename T> uint getID() { static uint id = registerClass<T>(); return id; } class...
Edit: changed the answer to make the Object untouched. template<class T> class Base<T> : public Object { public: virtual void applyPack(TemplatePack *p) { this->setTemplate(p->get<T>()); }; }; class Object2 : public Base<Object2> { // ... }; Edit: for the case of Object4, maybe the following will help: templa...
4,117,429
4,141,990
QWidget background color does not fully cover the QWidget
Using Qt Creator, I have set a QWidget's background property to black. However, some parts of the QWidget, more specifically, between QFrames/QGroupBoxes are still in its system's default color. Now, I thought that the QFrames and QGroupBoxes need to have its background property set to black too, but it did not work. I...
Found out the solution. It seems that you need to set the background color at the QMdiSubWindow, not at QWidget. Don't know why, but it seems logical.
4,117,430
4,117,650
C++ Packet Builder with Templates
PacketBuilder is a little Class which allow to write into a char* array. The Append Functions: template <class T> void PacketBuilder::Append(const T value) { memcpy((&m_Buffer) + m_Index, (const void*) &value, sizeof(T)); m_Index += sizeof(T); } Compiling without errors. If I call Append and use T as unsigned short ...
Your PacketBuilder is not a class template, as far as I can see. PacketBuilder::Append is however a template method, which requires that it's definition must be visible at any point of instantiation of this method. The only really safe way to assure this is to put the complete definition of this method template into th...
4,117,483
4,117,494
Find out inheritance relation between two objects classes in c++
I've got an abstract C++ base class CPlugin. From it, there are many classes derived directly and indirectly. Now given CPlugin *a,*b I need to find out, if a's real class is derived from b's real class. I.e. I'd like to do something like this: void checkInheritance(CPlugin *a, CPlugin *b){ if (getClass(a).isDerived...
You cannot do this in C++. The only way to get some information about types on runtime is RTTI. RTTI is not powerful enough to do what you need though. Please explain what you are trying to achieve, then you will get better answers.
4,117,507
4,117,559
Alternatives for gmake?
I have a c++ program file with two functions in it. If I change the first function alone, why should both of them have to be recompiled? Is there any build system which recompiles the first one alone and put it back in the same object file? Is this possible? The instructions of one function shouldn't depend on other ri...
The analysis to decide which semantic parts of a given source file have changed and thus need recompiling would likely outweigh the cost of the compilation itself in most cases. Build systems get big wins by analyzing the dependencies between source files because the cost of file I/O (particularly for include files) is...
4,117,538
4,117,605
How to be sure a method is overriding an existing virtual one in C++?
Let's suppose we have a base class which has a virtual method: class BaseClass { virtual void MethodToOverride() const { DoSomething(); } }; And a derived class which overrides the method (depending on the situation we can make it again virtual or not): class DerivedClass : public BaseClass { v...
C++0x offers an attribute for this (see vitaut's answer), and e.g. Visual C++ offers a language extension. But in portable C++98 the best you can do is a sanity check, that the base class offers an accessible member function that accepts the same arguments, like ... // The following macro is mainly comment-like, but pe...
4,117,648
4,117,748
Socket Server vs. Standard Servers
I'm working on a project of which a large part is server side software. I started programming in C++ using the sockets library. But, one of my partners suggested that we use a standard server like IIS, Apache or nginx. Which one is better to do, in the long run? When I program it in C++, I have direct access to the ra...
"Server side software" could mean lots of different things, for example this could be a trivial app which "echoes" everything back on a specific port, to a telnet/ftp server to a webserver running lots of "services". So where in this gamut of possibilities does your particular application lie? Without further informati...
4,117,675
4,117,687
Addressing a vector inside vector of vector pointers
To implement an open hash table in C++, I thought I'd define a vector that contains pointers to vectors containing data. For the sake of simplicity, let's say I want a hash table that can store ints. I assumed I needed a vector< vector<int>* > for that. The resulting data structure could look something like this: [ind...
(*myHashtable[i])[j] Subscript operator ([]) binds more tightly than dereference (*) (see http://www.cppreference.com/wiki/operator_precedence). Therefore you need to force the binding by using parentheses. Incidentally, you could write you inner loop thus: for (vector<int>::iterator it = myHashtable[i]->begin(); ...
4,117,914
4,117,965
the average of optical flow
I want to find the average of the optical flow, I could extract the features from the first frame and found their location in the next frame. Now, I want to find the average of the displacement in order to translate the image back to its stationary background in order to stabilize the image. // here I take the optica...
I am assuming from what you have written that you want to find the average displacement of all the feature points between the two frames. In that case all you have to do is compute the "hypotenuse" in a loop over the features, add up all its values, and then divide by the number of features. Ok, here's your answer: cv...
4,117,950
4,117,972
C++: how to get the type of a variable and use this as a template
I'm wriging a wrapper for C++ of a function declared in this way: class MyClass { public: template <class T> T& as(); }; My wrapper needs to eliminate the explicit template because I don't want to call myClass.as<int>(); So I tried to implement a new function declared in this way: class MyClass2 : public MyClass {...
This does not make sense. Why not just write: template <class T> void MyClass2::get(T & val) { val = as< T >(); } Since the type is a template-parameter, you need no typeof.
4,117,983
4,118,020
What's the standard way to login to a client software in c/c++?
To login to a website I can use curl, what about when I need to login to a client software?
Erm... there is no 'standard way' for logging into client software in C or C++ The concept of 'logging in' does not exist in any language that I am aware of. What you are after is some of API or library of code that will provide this functionality for you, or do it your self. Your question imply that's you are doing so...
4,118,025
4,118,050
Brace-enclosed initializer list constructor
I have class Phenotype with the following constructor: Phenotype(uint8 init[NUM_ITEMS]); I can create a Phenotype like this: uint8 data[] = {0,0,0,0,0}; Phenotype p(data); But I get an error when I try to create one like this: Phenotype p = {0,0,0,0,0}; Output: $ make g++ -Wall -g main.cpp -std=c++0x main.cpp: In fu...
It can only be done for aggregates (arrays and certain classes. Contrary to popular belief, this works for many nonpods too). Writing a constructor that takes them is not possible. Since you tagged it as "C++0x", then this is possible though. The magic words is "initializer-list constructor". This goes like Phenotype(...
4,118,066
4,118,116
The exercise 15.41 in book of c++ primer 4th
class Query{ friend Query operator&(const Query&,const Query&); friend Query operator|(const Query&,const Query&); friend Query operator~(const Query&); public: Query(const string&); //build a new WordQuery ?? Query(const Query&c):p(c.p),use(c.use){++*use;} ~Query(){delQuery();} Qu...
It appears that you put the prototype for the constructor, but you didn't actually put an implementation. You put: Query(const string&);, which says that there is a constructor somewhere that takes a string and creates a Query with it. However, somewhere you actually have to put something that does that.
4,118,176
4,143,494
libstdc++ parallel mode: Who's using it? Is it safe? Any similar projects?
the GNU implementation of the C++ Library supports a parallel mode, explained here. Any experiences in using it? Good ones? Bad ones? Especially regarding correctness, but also performance. Are there some "more or less serious" projects using it? Do you use it with the global turn-on-parallel switch -D_GLIBCXX_PARALL...
I've used it for some small projects, with a nice speedup for large stl operations. I never encountered any problems (I used the global switch). However I didn't really do much benchmarking, you might want to refer to studies like http://algo2.iti.kit.edu/singler/mcstl/parallelmode_se.pdf and http://ls11-www.cs.uni-dor...
4,118,301
4,118,893
can vertices coincide in convex polygons?
I am new to openGL and I am reading the redbook. Now, as an exercise I want to manually draw a sphere. For that I am dividing the sphere into slices and stacks, and thus I get multiple rectangles, but near the poles of the sphere I get triangles. (hope this was clear what I am doing). Now I know that if you draw a poly...
This is no problem whatsoever. OpenGL always has to be able to deal with the possibility of rasterising geometry where multiple vertices fall in the same location since even different input points may end up as the same output point depending on your modelview and projection matrices (or your geometry and/or vertex sha...
4,118,412
4,118,457
'Inaccessible direct base' caused by multiple inheritance
Spoiler alert: Maybe a stupid question. :) #include <iostream> using namespace std; class Base { public: virtual void YourMethod(int) const = 0; }; class Intermediate : private Base { public: virtual void YourMethod(int i) const { cout << "Calling from Intermediate" << i <...
This has nothing to do with overriding functions. It has to do with conversions. It really doesn't have to do with accessibility (i.e "private" or such) directly either. Here is a simpler example struct A { int a; }; struct B : A { }; struct C : B, A { }; // direct A can't be referred to! You can refer to the indirect...
4,118,523
4,118,780
How to convert mathematical matrix to Direct3D matrix?
When representing a mathematical matrix, rotations are performed as follows: http://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations Rx(θ) = 1 0 0 0 cos θ -sin θ 0 sin θ cos θ Ry(θ) = cos θ 0 sin θ 0 1 0 -sin θ 0 cos θ Rz(θ) = cos θ -sin θ 0 sin θ co...
I've always traced this confusion back to the late 80s. As I remember it, there were two particularly influential books on graphics at the time. One of them wrote vectors as row vectors on the left of matrices; the book was quite hardware oriented - conceptually you thought of the vectors as flowing left-to-right thr...
4,118,636
4,118,735
Problems with getting my Icon to show up in VS 2008
I have searched on this forum and haven't been able to find a solution to my problem. I have been trying to add an icon for my program to show up on the taskbar and for the exe but everything I've tried has been failing. I have gone to resource view and added my icon as a resource. the rc file came up but when I compil...
First, create an ICO format bitmap file that contains the icon image. This can be done with e.g. Visual Studio: Select "File|New...", then select the "File" tab in the dialog that appears, and choose "Icon". Store the ICO file in your application's source code directory, for example, with the name, "myappico.ico". The...
4,118,732
4,118,787
C++ array assign error: invalid array assignment
I'm not a C++ programmer, so I need some help with arrays. I need to assign an array of chars to some structure, e.g. struct myStructure { char message[4096]; }; string myStr = "hello"; // I need to create {'h', 'e', 'l', 'l', 'o'} char hello[4096]; hello[4096] = 0; memcpy(hello, myStr.c_str(), myStr.size()); mySt...
Because you can't assign to arrays -- they're not modifiable l-values. Use strcpy: #include <string> struct myStructure { char message[4096]; }; int main() { std::string myStr = "hello"; // I need to create {'h', 'e', 'l', 'l', 'o'} myStructure mStr; strcpy(mStr.message, myStr.c_str()); return 0; ...
4,118,758
4,118,802
How to impose interface?
How I should make sure that classes needed as a one of params to my templated class will have a certain interface? I know that one way is to make in Interface class pure virtual but I would like to avoid it. Is there any other way to do it? I would like to avoid anything which isn't standard //Example templa...
A simple solution is to have a dummy function that validates the requirement. Example: class Interface {}; // Basically a no-op, but has to compile. template<typename I, typename T> void require () { T * t = 0; I * i = t; } template<class SomePolicy> class My { void fnc () const { // won't...
4,118,899
4,118,903
Structure inheritance in C
Is it possible to inherit structure with another in standard C or C++?
C does not support inheritance. C++ does support inheritance.
4,118,933
4,118,949
set_terminate function is not working for me
I have the following code taken from cplusplus.com: // set_terminate example #include <iostream> #include <exception> #include <cstdlib> using namespace std; void myterminate () { cout << "terminate handler called\n"; abort(); // forces abnormal termination } int main (void) { set_terminate (myterminate); th...
One possibility - if you are running the program inside VC++ debugger, the debugger catches unhandled exceptions and it might not return control back to the running program to run myterminate. Try to run your program outside Visual C++.
4,118,954
4,118,977
Validation of string and date input in c++?
I just started c++ today. I am doing some simple registration program. I want to validate the input. I got stuck when validate fullname and birth_date. Here is my requirements: Fullname: I just want to check if its empty and no punctuation date_birth: i know this is abit tricky. But if I could validate if the input is...
Well, I'll try to steer you in the right direction. Firstly, in order to validate the string, you'll need to iterate over it character by character. You can do this using iterators and a for loop. The string class has a begin() and end() method, which you can use to loop over the whole string and examine each charac...
4,118,982
4,278,549
Customize the C++ scintilla lexer
Where can I tell scintilla to recognize different keyword sets ? I want to color them differently, just like notepad++ does.
Well scintilla behaviours are quite hard-coded, so it's quite delicate to tweak a lexer. I gave up using Qscintilla or scintilla, and switched to TextAdept, which use LUA to build lexers. The mac version seemsto have some speed issues, but I guess it will be fixed (or not) when it will come as a portable .app (let us p...
4,119,035
4,119,450
How to determine the type of a drive?
I am trying to figure out the device type for a particular drive. I'd like to know how to do it on Mac OS X and Linux as well, but for now if that's too much a Windows solution would suffice. so, let's say I have a drive H. I can determine if the device is a removable drive through the Win32 API function GetDriveType()...
Is the device class what you want? If so you can try libusb (available for win32). Use libusb_get_device_descriptor function.
4,119,482
4,119,547
SFINAE construct problem
I'm trying to implement is_base template and I have "a little problem". Why this doesn't work as it's suppouse to? #include <iostream> using std::cout; class Car { }; class Fiesta : public Car { }; template<class Base, class Derived> struct isBase { typedef char yes[2]; typedef char no[1]; template<clas...
You're explicitly providing a value for the pointer: f<Base,Derived>(0, 0), no conversion needs to occur here, especially not a derived-to-base one; this test will always pass, as the first one is always callable (any pointer can be null). You want something like this: template<class Base, class Derived> struct isBase ...
4,119,589
4,319,673
boost::asio with SSL - problems after SSL error
I use synchronous boost::asio SSL sockets in my application. I initialize all parameters and then connect to some hosts (one after another) and do a GET request for each host. Everything works until I get a "404 - Not Found" error for one of the hosts. After this error, all new connections fail with some unspecified SS...
I got the answer from the asio mailing list (many thanks to Marsh Ray). Sam Miller was correct in that the asio::ssl::context has to be created each time. To achieve this, std::auto_ptr is used. Connector.h: std::auto_ptr<asio::ssl::stream<tcp::socket>> sslSock; Connector.cpp: asio::ssl::context ctx(ioserv, asio::ssl:...
4,119,620
4,119,652
Reading tokens from file (complicated)
I have a basic tokenization structure/algorithm in place. It's pretty complicated, and I hope I can clarify it simply enough to enlighten you about the "flaw" in my design. class ParserState // bool functions return false if getline() or stream extraction '>>' fails static bool nextLine(); // reads and tokenizes next l...
Why not simply make m_buffer an std::istringstream instead of a std::string? You would remove a temporary variable as well as get the desired effect. Whenever you change m_buffer in statements such as m_buffer = ... write this instead: m_buffer.str(...);
4,119,818
4,119,885
Undefined symbol issues when using OpenMS namespace
I'm trying to get some sample code to work happily with OpenMS and running into a great deal of trouble. I have (just a small sample program that shipped as an example): #include <OpenMS/FILTERING/SMOOTHING/GaussFilter.h> #include <OpenMS/FORMAT/MzMLFile.h> #include <OpenMS/KERNEL/StandardTypes.h> #include <stdio.h> u...
Try compiling it to an object file (-c) and see if the problems still occur. E..g.: Is this a compiling issue or a linking issue? Also: Should there be a -L flag to search a particular library path? Should there be a -l flag to link in a particular library?
4,119,893
4,119,922
C++: POD and POD-wrapping objects
Often I declare classes to wrap a single Plain Old Data value; simple classes without virtual functions, like: class Velocity { int vel; public: // functions to work with velocity ... } Working with such object is the same as working with POD values? -- Is there any difference in space or time usage, if in my...
Working with such object is the same as working with POD values? No. You are not totally safe to use memcpy and friends on it (only allowed on PODs!). Can I cast a pointer or an array of such objects as a pointer/array of POD values and viceversa? If it is a POD, you are perfectly safe. But this is not a POD becau...
4,119,911
4,489,981
playing with GCC 4.6 on windows
I am very pleased to find out that GCC 4.6 supports the range-based for loop. I found an experimental release of MinGW 4.6 on xvidvideo.ru, is that a well-known, reliable website? What other options do I have (besides compiling myself from source code)?
I'm not really familiar with the site you linked as it's in Russian. The only other place I've found that offers current snapshots of GCC's build is from Equation Solution. I downloaded gcc4.5.1 from there and it's been working fairly well for me. I haven't tried the 4.6.x release yet however. Rumor has it that gcc 4.6...
4,120,169
4,121,910
MSVC - boost::python static linking to .dll (.pyd)
I got a VS10 project. I want to build some C++ code so I can use it in python. I followed the boost tutorial and got it working. However VS keeps to link boost-python-vc100-mt-gd-1_44.lib but it's just a wrapper which calls boost-python-vc100-mt-gd-1_44.dll. That's why I need to copy the .dll with my .dll(.pyd) file. S...
What libraries are linked depends on the settings of your project. There are two possibilities: You can build against statically dynamically linked versions of the c-runtime libs. Depending on which option is selected, the boost sends a proper #pragma to the linker. These options need to be set consistently in all pr...
4,120,242
4,120,256
Function takes a reference parameter with a default value
Based on http://www.cplusplus.com/reference/stl/vector/vector/ explicit vector ( const Allocator& = Allocator() ); This vector constructor takes a reference parameter which has default value of Allocator(). What I learn from this function signature is that a function can take a reference parameter with default value....
Const references may be bound to temporary objects, in which case the lifetime of the temporary extends to the lifetime of the reference.
4,120,313
4,120,360
How to create a class that would have a 2 threads inside and array of public methods that are not in that threads? (C++, using Boost librarys)
So I want a C++ class to contain for example one public function: int summ(); that would return an int which would be created as sum of 2 variables (each of that variabes should be edited by one thread) So generaly I need a sample like this: #include <iostream> #include <boost/thread.hpp> namespace this_thread = boost...
The example is a little strange, as the results would be random, depending on the exact coordination of the threads and sleep times. However, to get what you want, you have several options. You could create a new class with: The code of your main function as a class method; The c (sum) variable would be a class membe...
4,120,660
4,120,729
How to test if one rect is in another rect?
Alright, so I'm working on a game and I have found out that my enemies don't like my collision detection that works perfectly for my player. After a little debugging I found out it's because my enemies are bigger than my tiles, while my player is smaller than my tiles. Now I need to be able to make big enemies and bos...
In Java, use intersects(Rectangle r).
4,120,675
4,123,292
qHash function for QRect
What is the best way to calculate the qHash value of a QRect? I need to use QRect (and maybe QRectF) as the key of QCache. Right now I am using something like this: inline uint qHash(const QRect & r) { return qHash(QByteArray::fromRawData((const char*)&r, sizeof(r))); } It seems to work but I don't like casting it in...
I would simply do return qHash(QString("%1,%2,%3,%4").arg(r.x()).arg(r.y()).arg(r.width()).arg(r.height()))) Also I've found this solution: http://thesmithfam.org/blog/2008/01/17/using-qrect-with-qhash/ (read comment)
4,120,858
4,120,908
Finding the day of the thirteenth of every month over a period of years
I am currently trying to solve some problems from the USACO training website in preparation for an unrelated C++ programming competition. However, I am stuck on this problem: Does the 13th of the month land on a Friday less often than on any other day of the week? To answer this question, write a program that will com...
As Denny says, N is so small that you can easily iterate through the months using a table of days-in-a-month and a simple is-a-leap-year predicate to handle February. Just find out what day the 13th of Jan was in 1900 and then add up the elapsed days until 13th Feb, then 13th March etc.. Use a % operator to wrap the ...
4,120,868
4,120,878
Providing an instanceable class's method as a function pointer?
Here is what I'd like to do. I have a function pointer which wants a function like this: void func(int a); so I have a class: class Foo { public: void func(int a); }; Foo *foo = new Foo; something->setFunction(foo->func); or in my case: testWidget[count] = new TestWidget; testWidget[...
Is there a way I could make this work without using a static function? No. You can't convert a pointer to member function to an ordinary function pointer. If the callback accepted any callable object (or a std::function, for example), then you could bind the object to the member function and pass the result of that...
4,121,067
4,121,140
Need Design Advise C++: Want to implement a threaded queue for other threads to pass data
I've not done any thread programming before, so i wanted to ask you guys for some design suggestions and also about stuffs i should be aware of about thread programming. Environment: MFC/C++, VS2005 Problem: I have a vendor library running threads to poll data and receive reports from devices. Number of threads can rea...
You might want to check out intel TBB, http://www.threadingbuildingblocks.org/files/documentation/a00129.html seems to possibly do exactly what you want.
4,121,085
4,121,159
How can I rotate a Box2D body without applying a force to it?
Anyone know? All I can see is ApplyTorque and SetAngularVelocity, I want to just rotate the object before adding it to the simulation, for example: so I have one crate tilted up against a wall and another flat.
Use SetTransform, you can specify the position and orientation of your object.
4,121,125
4,121,156
operator overloading outside of a class!
when i was trying to seperate the declaration and implementation of a non-member overloaded operator, i got a LNK2001 error in VC2010, my code was like this: -foo.h- class A { public: A(float x); float x; }; A operator +(const A&, const A&); -foo.cpp- A::A(float x) { this->x = x; } A operator +(const A& l...
I suspect you have the definition in a different namespace than the declaration. ADL is finding the declaration (since it's in the same namespace as the class), and then you get an unresolved external error during link. e.g. -foo.h- namespace aspace { class A { public: A(float x); float x; }; A o...
4,121,173
4,125,229
How do I forward declare HANDLE? (Win32)
How do I forward declare HANDLE? I don't want to include all of windows.h in this particular header.
The header that actually typedefs HANDLE is winnt.h. Unfortunately this is 15K lines - here, so fixing your issue by including the slimline windef.h is a bit misleading. Here is the relevant part on my system (obviously the details could change from revision to revision, but won't change at the implementation level ...
4,121,235
4,121,258
Invalid HWND for parent
Is it possible to have a valid HWND with a valid parent, and then the parent become invalid without the child becoming invalid?
No, see the documentation for DestroyWindow: If the specified window is a parent or owner window, DestroyWindow automatically destroys the associated child or owned windows when it destroys the parent or owner window. The function first destroys child or owned windows, and then it destroys the parent or owner window. ...
4,121,296
4,121,396
Do Ideone and Codepad really not support C++03?
My question is related to Prasoon's question about non POD types and value initialization. I tried the following code on online compilers like Ideone and Codepad but the executables gave runtime error on both the sites. #include <iostream> #include <cassert> struct Struct { std::string String; int Int; boo...
Does that mean neither of them support C++03 value initialization feature? Yes. Prior to version 4.4, GCC did not completely support value initialization (the Boost GCC compatibility header explains this and has links to the relevant GCC defect reports; see line 77). If your code needs to be portable, you should be v...
4,121,392
4,121,399
C++ Error on compile
I am developing a firewall application which is complete for Windows XP. To accomplish this, I am creating a dll file, which can be used in C# file. For Vista or later, I used this code, but it's not compiling. I have win sdk 2008 and it is showing this error: Error 19 error LNK2019: unresolved external symbol _Fwpm...
You are missing a library reference. Check that you have imported the .lib that your code is expecting. EDIT: The missing import is from the library you're talking about itself. That probably indicates you forgot to import the .lib of that actual library, or you need to attach the .cpp files from that project into your...
4,121,429
4,121,537
C++ -- Why should we use explicit in this constructor?
Please refer to Wikipedia:Strategy Pattern (C++) class Context { private: StrategyInterface * strategy_; public: explicit Context(StrategyInterface *strategy):strategy_(strategy) { } void set_strategy(StrategyInterface *strategy) { strategy_ = strate...
Well, explicit constructors are always safe, but can be inconvenient. explicit ensures a compilation error should you provide a StrategyInterface* where a Context is expected. In doing so, it prevents construction of a temporary Context. This becomes particularly important in certain circumstances, e.g.: Context ta...
4,121,520
4,121,527
Linux C++ gdb command for user input
I am coding in C++ in Linux. I have handled the ctrl C signal so that I could clean up all the resources upon exit. However, I have the problem when I run gdb. Ctrl C is also the stopping of the gdb command. Hence, how do I send the ctrl C to my programme so that I could test my written resource clean up code? Thanks.
At gdb's command prompt: signal SIGINT
4,121,544
4,157,294
How do I create a dynamically loadable version of RtAudio in OSX
I need to create librtaudio.dylib, a dynamically loadable RtAudio library (http://www.music.mcgill.ca/~gary/rtaudio/). I'd like to write CFFI bindings (in SBCL) but I can't seem to compile a dylib that is loadable using CFFI. Here are the compiler and linker commands I'm using to create the dylib: g++ -O2 -Wall -Iinclu...
It seems that CFFI's C++ support is not adequate to load RtAudio, as it is a C++ lib. A workaround is to write a C wrapper around RtAudio and then write bindings to the wrapper.
4,121,610
4,121,702
Just beginning C++ in Xcode
...and I mean LITERALLY just beginning. As in, I just started earlier today. All I want to do is figure out how to build and run a 'hello_world' code from my textbook, but the 'build and run' button will not light up. I have read through 'Xcode Features Overview' as well as checking out at some help forums, and it's c...
In the "New Project" window, select Application > Command Line Tool, and choose "C++ stdc++" from the Type drop down.
4,121,822
4,122,121
Boost:Serialization: Who cleans up the deserialized data?
I'm serializing and sending a raw-pointer of an object to another application. When deserializing I'm getting another raw-pointer. This means that Boost::Serialization is constructing the object behind this pointer internally. I'm now curious who has ownership of the object and if Boost will delete that object, if it i...
My understanding of the documentation regarding pointers serialization is that ownership is kept by the archive : "Loading the same pointer object multiple times results in only one object being created, thereby replicating the original pointer configuration". This tends to indicate that the library handles the book ke...
4,121,855
4,121,869
Help with objects in C++
I have the code class ogre { public: int health; bool isalive; string name; }; int fight() { cout << "You're now fighting an ogre!" << endl; ogre ogre; player player; int ogredamage; int playerdamage; srand(time(NULL)); ogre.name = "Fernando Fleshcarver"; ...
ogre.isalive = true is an assignment! The while loop will always run because the result of the assigment is always true. You need == to test for equality. Better yet, just use while(ogre.isalive)
4,122,014
4,122,394
Implement copy-ctor in terms of copy-operator or separately?
This is not a duplicate of Implementing the copy constructor in terms of operator= but is a more specific question. (Or so I like to think.) Intro Given a (hypothetical) class like this: struct FooBar { long id; double valX; double valZ; long valN; bool flag; NonCopyable implementation_detail; // canno...
In general, I prefer b) over a) as it explicitly avoids any default construction of members. For ints, doubles etc. that isn't a consideration, but it can be for members with expensive operations or side effects. It's more maintainable if you don't have to consider this potential cost/issue as you're adding and remov...
4,122,063
4,123,164
Zip Archive Library decompression with AES-256
I am using Zip Archive library for compressing and decompressing files, i needed to enable AES encryption so by Uncommenting #def ZIP_AES in the _features.h file included with the library and recompiling I got CZipException for decompression "WinZip AES encryption has not been enabled for the library, but is required...
Thanks to Oli Charlesworth; there was a conflict between the lib file produced from the free library and the one i bought thanks a lot.
4,122,066
4,122,147
OpenSSL - How to determine the right length of an rsa encrypted string?
I use OpenSSL to encryt a string. After that I want to encode the encrypted string with base64 algorithm also using OpenSSL. So I found the following code snipped: ( bit.ly/adUSEw ) char *base64(const unsigned char *input, int length) { BIO *bmem, *b64; BUF_MEM *bptr; b64 = BIO_new(BIO_f_base64()); bmem = BIO_new(BIO_...
The size of the encrypted message is exactly the size of the modulus in the private key. You have to get the information from there. You cannot use strlen because the buffer with the encrypted message is likely not null-terminated, and the encrypted message may contain (and will likely contain) null bytes.
4,122,214
4,122,229
Why operator = doesn't get inherited from a template class
I have following template code: class ClassName{}; template <class T> class TemplatePtr { public: void operator=(T* p) { } }; class TemplatePtr_ClassName: public TemplateePtr<ClassName> { public: ~TempaltePtr_ClassName(); }; void Test() { TemplatePtr_ClassName data; data = new ClassName; } ...
operator = is always hidden by the derived class implementation unless explicit using declaration is provided. This is true for both class templates and ordinary classes. BTW, your declaration of operator= is very nonstandard. It is usually declared so for a class 'A'. A& operator=(A const &); Here is something that m...
4,122,304
4,126,573
secure log in and session management for iphone app
I have a server (not a web server but just low level tcp socket server), and I want to know how to log in securely through iphone (probably using ssl), manage session and communicate with the server(probably using aes). My idea is "use ssl to log in and exchange aes key" and "use that aes key to communicate later." Som...
Have a look at CFReadStream and CFWriteStream. You can setup SSL Connections with the CFStream types as well. To setup an SSL connection you need somthing similar to this: NSString *host = @"example.com"; unsigned port = 1234; CFReadStreamRef readStream; CFWriteStreamRef writeStream; CFHostRef remoteHost = CFHo...
4,122,419
4,122,439
C++ : problem when trying to create an instance
Still trying to get back into C++ and fumbling on differences from Java. Can anyone tell me what's wrong here? Test.h #ifndef TEST_H #define TEST_H class Test { public: int x, y; Test(); virtual ~Test(); protected: private: }; #endif // TEST_H Test.cpp #include "Test.h" Test::T...
You use new with pointers in C++. It is different from Java. Your declaration of Test test_obj should be Test* test_obj; However, you can declare variable simply on stack like Test test_obj;. Doing this means that you don't have to new the object, the constructor is automatically called and hence, object is initialized...
4,122,551
4,123,468
Using Microsoft Detours - bunch of undefined's
I tried searching the compiler errors on google, but it didn't even return a search result. So, i'm a little lost here. I just downloaded microsoft detours, built it and got the detours.h, detours.lib, detoured.lib, and detoured.dll files from it. Then, trying to use it in my own project, i get the following errors: ht...
They are not compiler errors, they are linker errors. Something is very broken in the way you build this, you are linking the wrong version of the CRT. Even the new and delete operators are undefined, suggesting that you don't link the CRT at all. Very hard to do when you use the MSVC compiler. Document how you bui...
4,122,607
4,125,194
C++ using Namespace In Source Files
Say I'm making a project and I have most the project in a namespace named Project. I define a class inside the namespace Project named MainProject. In the source file, to implement the class, do I do 'using namespace Project;' or do I wrap it in a 'namespace Project { ... }' nest?
Given a header "n.h": namespace n{ extern void f(); } The following does not define f() in namespace n (from here on, I'll refer to it as n::f: #include "n.h" using namespace n; void f(){ } If you try to refer to n::f anywhere, you'll get a link-time error. The above defines an f in the global namespace. This does...
4,122,609
4,123,540
Free installer make it easy to install application as Windows services?
Is there any free installer allow user to seamlessly install a software that could also install Windows service? There are a few ways like sc.exe but in Windows Vista and 7, they are denied by default unless they user grant themselves as administrator. Hope there a software make life easy for developers. I did tried a ...
You could try using NSIS with the NSIS UAC plug-in, then use NsSCM or similar.
4,122,624
4,122,717
Would you implement a lightweight XML parser with <regex>?
If you had to implement a lightweight XML parser, would you choose to use regex? The XML parsing in my case would be most simplified: only tags and text content. No namespaces, no attributes, no schema support (at the beginning surely, but maybe...). I think it would be a good exercise for me to learn the new C++0x <r...
In a word: no. XML is not a regular language. UPDATE (To expand, based on the discussion in the comments below) XML is not regular, so you cannot hope to use regexes to perform some sort of one-hit parse/split operation on the entire file/string. Whilst you could write a state-machine-based parser that uses regexes to...
4,122,789
4,122,835
Copy object - keep polymorphism
The following code tries to copy an object and keep the original type. Unfortunately it does not work (every copied object will become a Super instead of being of the same class as its original). Please note that copySuper(const Super& givenSuper) should not know anything about the subclasses of Super. Is it possible t...
Try this: class Super { public: Super();// regular ctor Super(const Super& _rhs); // copy constructor virtual Super* clone() const {return(new Super(*this));}; }; // eo class Super class Special : public Super { public: Special() : Super() {}; Special(const Special& _rhs) : Super(_rhs){}; virt...
4,122,792
4,122,880
what is the 'what' command on AIX under LINUX
I am used to use what to find out some version string in my program, which is normal defined as a string in the c++ code, starting with "@(#)". Now I cannot find it in Linux. Can anyone tell me what I am supposed to do? Thanks a lot!
The what command is part of the Source Code Control System (SCCS), which is not commonly available on Linux (if there is a Linux version at all). You can try to emulate it with the strings command: strings a.out | fgrep '@(#)' Reimplementations of what are available in CSSC (an SCCS-to-modern version control conversio...
4,122,858
4,122,947
How to put function inside a class into thread? (C++ using Boost)
I have a class with some functions like printf("hello main thread"); and printf("hello thread created inside class");. Each can theoreticaly use class variables. How to put one of that functions into thread? (C++ using Boost libraries)
typedef boost::shared_ptr<boost::thread> thread_ptr; class your_class : boost::noncopyable { public: void run(); void join(); void signal_stop(); private: void your_thread_func(); thread_ptr thread_; }; void your_class::run() { thread_ = thread_ptr(new boost::thread(boost::bind<void>(&your_c...
4,122,952
4,123,542
may a whole array reside in some cpu register?
As I'm not too much familiar with cpu registers, in general and in any architecture specially x86 and if compiler-relevant using VC++ I'm curious that is it possible for all elements of an array with a tiny number of elements like an array of 1-byte characters with 4 elements to reside in some cpu register as I know th...
Within a single function, an array could be held in one or more registers, just so long as the compiler is able to produce CPU instructions to manipulate it as the code dictates. The standard doesn't really define what it means for something to "be" in a register. It's a private matter between the compiler and the debu...
4,122,986
4,123,005
How to make boost threads self-destruct? (C++)
I have a class with some function like: void workerFunc(int ClassVariable) { boost::posix_time::seconds workTime(classVariableA); std::cout << "Worker: running" << std::endl; // Pretend to do something useful... boost::this_thread::sleep(workTime); std::cout << ClassVariable << std::...
You do not have to do anything for that. You just have to make sure that the thread really finishes (i.e. no infinite loops or such).
4,122,991
4,123,054
redirect standard output to a file using multiple thread
I tried to redirect standart output (cout) to a file, for debugging purposes std::ofstream traceFile; traceFile.open("c:/path/file.txt"); std::streambuf* fileBuff = traceFile.rdbuf(); std::cout.rdbuf(fileBuff); std::cout << std::unitbuff; std::cout << "disk is written\n"; But calling cout from a new thread make the...
This example works fine for me, whilst your test case doesn't. On my machine your code seemed to double free the streambuf from the file, whereas this example swaps it back before the destructors are called.
4,123,398
4,124,198
Strange default constructor syntax
Saw the following in some legacy code: class A { &A() { ... } } What "&" is used for? It compiles in VC++ 2008 and looks like default constructor, bug gcc fails to compile it.
Although syntactically & is allowed in this position in the grammar (it's an example of a declarator that is the sequence: ptr-operator declarator, & being a ptr-operator), semantically it has no meaning and is not allowed here. The fact that it is valid purely from a grammatical point of view may indicate why Visual S...
4,123,550
4,123,568
Can I use the not operator in C++ on int values?
Strange question, but someone showed me this, I was wondering can you use the not ! operator for int in C++? (its strange to me). #include <iostream> using namespace std; int main() { int a=5, b=4, c=4, d; d = !( a > b && b <= c) || a > c && !b; cout << d; system ("pause"); return 0; }
Yes. For integral types, ! returns true if the operand is zero, and false otherwise. So !b here just means b == 0. This is a particular case where a value is converted to a bool. The !b can be viewed as !((bool)b) so the question is what is the "truthness" of b. In C++, arithmetic types, pointer types and enum can be ...
4,123,618
4,132,175
How to add compiler include paths and linker library paths for newly installed Boost?
I have RHEL 5.2, with Boost 1.33 installed. I downloaded boost_1_44_0.tar.bz2. and built it. On completion it showed: The Boost C++ Libraries were successfully built! The following directory should be added to compiler include paths: /home/dfe/Archive/boost_1_44_0 The following directory should be added to linke...
First, I removed the existing boost rpm using rpm -e boost-1.33.1-10.el5 A message is displayed saying "error: "boost" specifies multiple packages" Then tried: rpm -e --allmatches boost (I don't remember whether I typed 'boost' or 'boost-1.33.1-10.el5') The packages with dependencies were shown. I did: rpm -e [packag...
4,123,744
6,727,517
How to disable WebCam diode programmatically
In my laptop (Dell) strong blue diode light while WebCam use is annoying me. I was thinking to disable it. Do you know any library or method to turn off this diode light?
I have done this, and it is completely possible without hardware modification on MOST (if not all) Dell webcams compatible with the Dell webcam software. With older Dell Webcam Center software and drivers (~pre 2008), there is a setting which controls the LED during motion capture and it can be easily changed in the GU...
4,123,809
4,124,790
Automatically Instantiating over a bunch of types in C++
In our library we have a number of "plugins", which are implemented in their own cpp files. Each plugin defines a template function, and should instantiate this function over a whole bunch of types. The number of types can be quite large, 30-100 of them, and can change depending on some compile time options. Each insta...
I've used http://www.boost.org/doc/libs/1_44_0/libs/preprocessor/doc/index.html for such magic, in particular SEQ_FOR_EACH.
4,123,830
4,124,453
how in C++ send file to browser
I need to send file from my directory to user. The problem file was not send. Can any one help me? My code is like: CHttpServerContext* pCtxt; // ... there i set headers for open DWORD dwRead; CString fileName = "c:\txt.doc"; HANDLE hFile = CreateFile (fileName, GENERIC_READ, FILE_SHARE_READ, (LPSE...
No point in re-inventing the wheel - just use the TransmitFile API instead - it is built into CHttpServerContent::TransmitFile().
4,123,938
4,127,843
Same function differing in parameter type - passing by value/reference
Edited: Please note, when I mention performance comparison, it is not performance comparison of C++ pass-by-reference vs. pass-by-value. It is more to test whether the underlying algorithm of CPLEX (to solve linear programs) runs better when CPLEX objects are passed by value or passed by reference. Hello All: I need to...
Here is what worked for me... #define PBV 0 //0 means PBR, 1 means PBV #if PBV == 0 #define PCLASS1 Class1& #elif PBV == 1 #define PCLASS1 Class1 #endif void function_to_call(PCLASS1 class1object){ //depending on PBV, PCLASS1 above will be either Class1& or Class1 //Stuff } This way, I did not have to ha...
4,123,964
4,123,987
Problem retrieving from map of lists
In my program, I have a map with string keys and list (of a user-defined class) values, defined like so: std::map<const char*, std::list<Show>> _shows; I have a function that adds to a specific list, like so: void Add(Show s, const char* index) { list<Show> lshow = _shows[index]; lshow.push_back(s); } However, every ...
The key in your map is the pointer value, not its contents. Therefore weird behavior. Change the map so that its key be std::string. Also, you modify the copy of your stored list. To avoid this, use a reference list<Show>& ls = map[index]
4,124,182
4,124,269
C/C++ encrypt/decrypt with public key
I'm looking for two functions conceptually similar to these: // returns the encrypted text string encrypt( string public_key, string pass_phrase, string text ); // returns the original text string decrypt( string private_key, string pass_phrase, string encrypted_text ); where string could be a char*, a std::string or ...
Unfortunately, encryption always requires a non-superficial knowledge of the algorithms involved. It is hard to get right. The "Handbook of Applied Cryptography" is a relatively readable guide to the various algorithms available so it's probably worth a look. You could also try cryptlib. It seems to have a well-layered...
4,124,271
4,137,633
std::vector of objects and const-correctness
Consider the following: class A { public: const int c; // must not be modified! A(int _c) : c(_c) { // Nothing here } A(const A& copy) : c(copy.c) { // Nothing here } }; int main(int argc, char *argv[]) { A foo(1337); vector<A> vec; vec.push_ba...
I'm not sure why nobody said it, but the correct answer is to drop the const, or store A*'s in the vector (using the appropriate smart pointer). You can give your class terrible semantics by having "copy" invoke UB or doing nothing (and therefore not being a copy), but why all this trouble dancing around UB and bad cod...
4,124,810
4,124,902
Explain "C fundamentally has a corrupt type system"
In the book Coders at Work (p355), Guy Steele says of C++: I think the decision to be backwards-compatible with C is a fatal flaw. It’s just a set of difficulties that can’t be overcome. C fundamentally has a corrupt type system. It’s good enough to help you avoid some difficulties but it’s not airtight ...
The obvious examples in C of non-type-safety simply come from the fact you can cast from void * to any type without having to explicitly cast so. struct X { int x; }; struct Y { double y; }; struct X xx; xx.x = 1; void * vv = &xx; struct Y * yy = vv; /* no need to cast explicitly */ printf( "%f", yy->y ); Of cou...
4,124,845
4,125,609
What determines an Xcode Project's developmentRegion setting?
I'm working on a C++ project using Xcode with another developer. Every time he opens the xcodeproj, his version of Xcode adds developmentRegion = English; to the project.pbxproj file inside the xcodeproj. Every time I open the xcodeproj, my version of Xcode removes the developmentRegion = English; line from the project...
I think it's related to your Xcode version, version 3.2.4 started adding that string, while previous versions don't (and are are removing it).
4,124,989
4,125,186
Does std::vector::swap invalidate iterators?
If I swap two vectors, will their iterators remain valid, now just pointing to the "other" container, or will the iterator be invalidated? That is, given: using namespace std; vector<int> x(42, 42); vector<int> y; vector<int>::iterator a = x.begin(); vector<int>::iterator b = x.end(); x.swap(y); // a and b still val...
The behavior of swap has been clarified considerably in C++11, in large part to permit the Standard Library algorithms to use argument dependent lookup (ADL) to find swap functions for user-defined types. C++11 adds a swappable concept (C++11 §17.6.3.2[swappable.requirements]) to make this legal (and required). The te...
4,124,998
4,125,036
Microsoft Visual C++ 2008 Redistributable Package - what files does it contain?
What files does the Microsoft Visual C++ 2008 Redistributable Package contain ? I would like to bundle the files with my application. Thanks
You can usually open the redistributable packages with an archive utility and take a look inside. I think 7-zip should do the trick here. It should handle both MSI packages and the old CAB package format.
4,125,033
4,125,074
Floating point division vs floating point multiplication
Is there any (non-microoptimization) performance gain by coding float f1 = 200f / 2 in comparision to float f2 = 200f * 0.5 A professor of mine told me a few years ago that floating point divisions were slower than floating point multiplications without elaborating the why. Does this statement hold for modern PC arch...
Yes, many CPUs can perform multiplication in 1 or 2 clock cycles but division always takes longer (although FP division is sometimes faster than integer division). If you look at this answer you will see that division can exceed 24 cycles. Why does division take so much longer than multiplication? If you remember back ...
4,125,210
4,125,338
How to break on every method of a class in GDB?
I have a class with a regrettable number of methods. I would like gdb to break whenever I enter the class, so through any of the methods. Is there a way to do this without setting break points individually for each method?
I never tried it myself, but it seems you can try the rbreak command : rbreak regex Set breakpoints on all functions matching the regular expression regex. This command sets an unconditional breakpoint on all matches, printing a list of all breakpoints it set. Once these breakpoints are set, they are treated just like...
4,125,536
4,125,966
number of matches in two sequences with STL
OK, here is yet another question of the "How to do it better in STL?" series. We have two ranges, designated by first1, last1, and first2. We want to find the number of different i's from [0, last1-first1] such that *(first1 + i) == *(first2 + i) For example: {a, b, c, d, d, b, c, a} {a, a, b, c, d, c, c, a} ^ ...
std::inner_product(first1, last1, first2, 0, std::plus<T>(), std::equal_to<T>()); UPDATE Konrad has pointed out in the comments below that this relies on slightly nefarious implicit conversion from bool to int. Whilst this is completely legal, it can be avoided thus: template <typename T> int match(const T &a, const ...
4,125,666
4,125,879
Boost, C++ how to kill thread opened by another thread?
so I have some main function. 24 time a second it opens a boost thread A with a function. that function takes in a buffer with data. It starts up a boost timer. It opens another thread B with a function sending buffer into it. I need thread A to kill thread B if it is executing way 2 long. Of course if thread B has exe...
The term you are looking for is "cancellation", as in pthread_cancel(3). Cancellation is troublesome, because the cancelled thread might not execute C++ destructors or release locks on the way out ... but then again it might; the uncertainty is actually worse than a definitive no. Because of this, boost threads do not...
4,125,905
4,126,105
Using std::function to call a member function while using templates
I have a templated class like this: template <typename T> class AguiEvent { std::vector<std::tr1::function<void(T, AguiWidget*)>> events; public: void call(AguiWidget* sender, T arg) const; void addHandler(std::tr1::function<void(T, AguiWidget*)> proc); void removeHandler(std::tr1::function<void(T, AguiWidget*)> proc...
Assuming that testWidget[0]->silly is a member function with the appropriate signature, it looks like you should be using TR1's bind to specify the object on which the member function will be called: function<void(T,AguiWidget*)> handler = bind(&TestWidget::silly, testWidget[0], _1, _2); testWidget[count]->eventMouseCl...
4,125,919
4,125,930
do while loop and others
when I modify string or another variable inside the loop it's condition is recalculated each time? or once before the loop start std::string a("aa"); do { a = "aaaa"; } while(a.size<10) and what about for loop
Every time. Basically it checks every time to see if the statement inside the conditional is true. If it is true, continue to loop, if it is false break the loop. That is why these constructs are called Conditional Loops