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,390,270 | 4,687,396 | How can I manage building library projects that produce both a static lib and a dll? | I've got a large visual studio solution with ~50 projects. There are configurations for StaticDebug, StaticRelease, Debug and Release. Some libraries are needed in both dll and static lib form. To get them, we rebuild the solution with a different configuration. The Configuration Manager window is used to setup which p... | Make a copy your original project file in explorer as CoreLib.vcxproj (in case of other VS check the appropiate extension)
Add CoreLib.vcxproj as an existing project to your solution and save your solution.
Go to the properties->Configuration Properties->General of CoreLib.
Select all Configurations (left upper corner)... |
4,390,356 | 4,390,400 | Using malloc Versus new | I've been using pointer = new type[size] for a while now and just recently discovered malloc.
Is there a technical difference between malloc and new? If so, what are the advantages to using one over the other?
| malloc is a function call, new in this case an expression.
The difference is; new will allocate memory and construct all the elements of that array with the default constructor. malloc just gives back a chunk of uninitialized memory.
Further still, ::operator new will throw std::bad_alloc or a new handler if one was re... |
4,390,499 | 4,390,559 | How do I call static members of a template class? | If I have:
template <class T>
class A
{
static void f()
{
// not using template parameter T
}
};
In this case A<int>::f() is same as A<double>::f(), but I don't want call A::f() via the template parameter. Is there a syntax that allows calling of f() but doesn't require the template parameter?
| The compiler doesn't know that A<T>::f() doesn't use type parameter T. So as it is, you must give the compiler a type any time you use f.
But when I'm designing a template class and I notice some members/methods don't depend on template parameters, I'll often move those up to a non-template base class.
class A_Base {
... |
4,390,733 | 4,390,930 | dynamically allocating atwo dimensional array where each row contains variable number of elements & freeing it in c++ | How can I dynamically allocate a two dimensional array where each row contains variable element? How can I free this memory?
| Actually you probably want a vector of vectors, something like this:
std::vector<std::vector<int> > vector_2d;
This way you'll benefit from the automatic memory management of the vector rather than having to manually manage the memory of an array of pointers to arrays of data.
|
4,390,820 | 4,390,887 | Placing a class object inside a vector? | I noticed that I can place a Class inside a vector; here is my program, where I am receiving the following error:
/out:blackjack.exe
blackjack.obj
blackjack.obj : error LNK2019: unresolved external symbol "private: static class
std::vector<class Card,class std::allocator<class Card> > Card::Cards" (?Cards@
Card@@0V?$... | You are declaring the static member Cards inside the class definition, but you aren't defining it anywhere. Add a definition after the class definition:
vector<Card> Card::Cards;
|
4,390,833 | 4,956,411 | What versions of gcc, llvm and clang are in XCode 4? | For some reason, this information is difficult to come by.
We'd like to start using some of the C++0x features that are available in most compilers. But we are held back a bit by XCode 3, since it only provides GCC 4.2 and LLVM 1.5. All of the other platforms we need to support either already have compilers with prel... | Xcode 4 GM
gcc version 4.2.1 (Apple Inc. build 5666) (dot 3)
Apple clang version 2.0 (tags/Apple/clang-134) (based on LLVM 2.9svn)
|
4,390,845 | 4,412,753 | Get Mouse Double Click with pyHook | I'm trying to get Mouse Double Clicks with pyHook, but instead I'm getting two pair entries of single clicks e.g. WM_LBUTTONDOWN (0x201) and WM_LBUTTONUP (0x202) . I'm expecting WM_LBUTTONDBLCLK (0x203). What am I misssing here?
import pythoncom, pyHook
def OnMouseEvent(event):
print event.Message, e... | The reason why you are getting two WM_LBUTTONDOWN and WM_LBUTTONUP and no WM_LBUTTONDBLCLK is because of what MrZebra says: the target window class' style does not include the CS_DBLCLKS style. Unless you can modify the source code for the target window class, it will never receive WM_LBUTTONDBLCLK, because Windows wil... |
4,390,888 | 4,866,616 | Move Constructor calling base-class Move Constructor | I have a base class that basically wraps up attaching a class to a arbitrary windows handle (e.g, HWND, HFONT), and uses a policy class to attach/detach and destroy:
// class SmartHandle
template<typename THANDLE, class TWRAPPER, class TPOLICY>
class SmartHandle : boost::noncopyable
{
private:
TPOLICY* m_pPolicy; ... | actually it should be like this.
Window::Window(Window&& _rhs) : SmartHandle( std::forward<SmartHandle>( _rhs ) ) { }; // eo mtor
http://msdn.microsoft.com/en-us/library/ee390914.aspx
|
4,390,945 | 4,390,979 | Understanding references vs. pointers. Why does this work? | It has become apparent through a series of SO questions today that I have only a poor understanding of the true nature of pointers, references, and values.
Consider the following code:
int* p = new int(3);
int& r = *p;
cout << " p = " << p << "\t*p = " << *p << endl;
cout << "&r = " << &r << "\t r = " << r << endl;
... | Even though you don't get an error, the results are still undefined. Undefined behavior means anything can happen, including your program appearing to continue to work correctly.
A reference is the same thing as an alias to the value at an address.
This is effectively true. It would be more correct to say that a re... |
4,391,030 | 4,391,152 | Can WCF be used with/from native (C++) applications? | What the question says. How do you interface with the WCF "world" from a native application, that does not have .NET available?
EDIT: Sorry, I should have been more specific as it appears that WCF covers such a broad spectrum. I was thinking of the case where you have several applications using WCF/TCP communication as... | WCF is protocol agnostic - well almost. But you need to consider this in the way you are going to communicate with WCF:
As long as you can send messages as the other side can use, you should be alright.
1) Named-pipe binding: It is propriety and difficult to use outside .NET
2) TCP binding: It is propriety and difficul... |
4,391,033 | 4,391,132 | Return value from local scope? | Bumped into some code like this in our code base... which made me worried.
int foo(int a); // Forward declaration.
int baz() {
int result = {
int a = dosomestuff();
foo(a);
} ? 0 : -1;
return result;
}
Is the behavior of this code well-defined?
Will it really work, that result variable ... | This is a GCC extension to C called 'statement expressions': http://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html
The key thing is that a statement expression returns the last thing it does as the value of the expression:
The last thing in the compound statement should be an expression followed by a semicolon; the v... |
4,391,178 | 4,415,315 | Reuse Boost thread (from threadpool) after interruption or join | At the moment I am using a producer consumer model for the rendering portion of a realtime graphics application. The consumer will continually look for data in our queue(infinite loop); however I am fearful that this may cause my simulation to get out of sync of the main loop. I think this is the fast producer slow con... | #1. I would do this by counting the amount in the queue after each render. If it too high, then either
a. Dump the queue
b. Set a boolean variable to false
That variable will be shared between the threads, and when the producer sees that it is false, it begins waiting on a condition variable. The consumer then notifies... |
4,391,192 | 4,391,256 | Why do I get cc1plus: error: unrecognized command line option "-arch"? | /usr/bin/make -f nbproject/Makefile-Debug.mk SUBPROJECTS= .build-conf
/usr/bin/make -f nbproject/Makefile-Debug.mk dist/Debug/GNU-MacOSX/cppapplication_1
mkdir -p build/Debug/GNU-MacOSX
rm -f build/Debug/GNU-MacOSX/main.o.d
g++ -arch i386 -c -g -MMD -MP -MF build/Debug/GNU-MacOSX/main.o.d -o build/Debug/GNU-MacOSX/m... | The -arch option is part of the Apple extensions to gcc. You need to use the gcc supplied by Apple's Developer Tools, Xcode.
|
4,391,193 | 4,394,792 | libx264 in Visual Studios 2010 - Memory error in Release Build | I am building an application and using the x264 library as an encoder. I have built the library for my windows system using MSys/MingW. The library works fine under debug build (note both debug and release builds are using the default VS2010 settings). However, under release an access violation error is thrown at the f... | Refer to a similar issue here, see if that helps you too.
EDIT
Post that you also want to run your application through AppVerifier
EDIT
In my opinion release "Build with debugger info" amounts to turning on -g switch together with optimization switches and turning off any DEBUG macro. Also if you debugger attached (u... |
4,391,202 | 4,391,268 | Symbol not found linking a library | I'm writing a simple game engine, and I have the EntityComponent.h file:
#ifndef Psycho2D_Core_EntityComponent_
#define Psycho2D_Core_EntityComponent_
#include <string>
namespace psycho2d{
class EntityComponent{
private:
std::string m_name;
public:
EntityComponent(const std::string &nam... | Put the code for the inline function in the header file, if you want to reference it from multiple .cpp files.
Reference here.
|
4,391,208 | 4,391,240 | C++ Iterators, interfaces and pointers | I'm trying to use c++ iterators with interfaces, but does not manage to make it working.
I'm a bit lost with what type to choose for the vector contents. Is this need to be a pointer ? do I have to make a "new Implementation()"? In brief, it is unclear to me, and I can't manage to find useful examples about that.
Here ... | Change *iterator->method(); to (*iterator)->method();
The former dereferences the return of iterator->method(). Interface* doesn't have a method(), it doesn't have anything.
You want to dereference the iterator to get to your pointer, and then dereference IT.
You've basically got the same thing as Iterator** so act ac... |
4,391,244 | 4,391,274 | Declaration and Implementation of Functions | According to my teacher, it's bad practice to write user-defined functions like this:
int DoubleNumber(int Number)
{
return Number * 2;
}
int main()
{
cout << DoubleNumber(8);
}
Instead, he says to always use forward declarations, even if the functions don't need any knowledge of each other:
int DoubleNumber(... | If you don't declare the forward declarations ("prototypes"), then you need to make sure that all your functions occur before any functions that depend on them, i.e. in the reverse order of the call graph. That's fine for a simple example as above, but is a complete pain for anything more realistic (and in some cases ... |
4,391,281 | 4,391,731 | Filling Matrix with data points | In openCV there's a function called FindHomography which takes MATRICES as input.
I have data points representing the location of the features in a frame. I want to put these data points in a Matrix using C++ or C.
I want to put them in 2d array, which these features represent x and y location.
Please can you suggest ... | Here's an example based on the example in O'Reilly's Learning OpenCV on page 35-36:
float vals[] = { 0.1, 0.2, 0.3, 0.4 };
CvMat mat;
cvInitMatHeader(&mat, 2, 2, CV_32FC1, vals);
This creates a 2x2 float Matrix using the statically allocated data above.
|
4,391,294 | 4,391,345 | Compiler Error when passing an array as a param in VC++ 2010 | This is possibly a newbie question, as I am just learning programming. I am learning about QuickSort algos, and I'm trying to pass an int array as a parameter to my function quickSort(). When I try to compile in VC++ 2010, I'm getting a compiler error.
I've looked up how to pass arrays as parameters, and tried to mirr... | As far as i understand, this is C, not C++.
If i understand right, you should put the prototype before the "line 16".
By prototype, i mean the line void quickSort(int aTest[], int left, int right).
|
4,391,350 | 4,391,373 | Can a object be passed as value to the copy constructor | I have some confusion with this "Can a object be passed as value to the copy constructor"
The compiler clearly rejects this, which means it is not possible.
Can you help me understand this?
class Dummy{
Dummy(Dummy dummy){ // This is not possible
}
};
Then why is it said that "Copy constructor will lead to re... | This is because in order to pass by value, you need to COPY the object. Therefore, you are passing in a copy of the object, in the definition of how to copy it.
Effectively what really happens if this trap is not there, is your copy constructor will call your copy constructor to create a copy, which will call your copy... |
4,391,372 | 4,391,396 | Use std::sort to find top N items in a std::vector | I need to sort the elements in a std::vector, but I'm only interested in the top N items being sorted, not the entire list:
E.g. in a list of 10 elements, only first 3 have to be sorted. Don't care about the rest...
1,2,3,6,7,4,9,8,5
Can this be done using std::sort?
Edit
I simply needed to find the top N items in a ... | Try std::partial_sort instead of std::sort. :)
|
4,391,467 | 4,391,489 | Declare array in C++ header and define it in cpp file? | This is probably a really simple thing but I'm new to C++ so need help.
I just want to declare an array in my C++ header file like:
int lettersArr[26];
and then define it in a function in the cpp file like:
lettersArr[26] = { letA, letB, letC, letD, letE, letF, letG, letH,
letI, letJ, letK, letL, letM, let... | Add extern to the declaration in the header file.
extern int lettersArr[26];
(Also, unless you plan to change the array, consider also adding const.)
The definition must have a type. Add int (or const int):
int lettersArr[26] = { letA, /*...*/ };
|
4,391,570 | 4,401,229 | PNG++ Read Pixel Color Values | How do I read the pixel color values in a png with png++? I dont see any way of reading values in the documentation. I need to get all the values rgba seperately and append them to a char array.
| can't add a comment, so here goes :)
Actually, you should want image[Y][X] since first [] gets you to Y-th row, and then to the X-th column in that row.
Btw, I'm the author of PNG++. Feel free to ask more specific questions on the mailing list or at my private email, or here, if you like. :)
|
4,391,655 | 4,391,708 | Associating and iterating in C++ | I've got a situation where I want to use an associative container, and I chose to use a std::unordered_map, because it's perfectly feasible that this container could be used to hold millions or more of elements. But now I also need to iterate in order. I considered having the value types link to each other in a list, b... | Well, you know the O() of the various operations of the two alternatives you've picked. You should pick based on that and do a cost/benefit analysis based on where you need the performance to happen and which container does best for THAT.
Of course, I couldn't possibly know enough to do that analysis for you.
|
4,391,875 | 4,392,339 | What is wrong with this Qt code? | I was reading MVC tutorial and wanted to try out the code, but for some reason (which I'm not able to figure out) it is not working.
This code is suppose to show contents of current directory in QListWidget.
#include <QApplication>
#include <QFileSystemModel>
#include <QModelIndex>
#include <QListWidget>
#include <QL... | There are 2 problems.
The first described by Frank Osterfeld's answer. Move:
QListWidgetItem *newItem = new QListWidgetItem;
into your loop.
The second has to do with QFileSystemModel's threading model. from the docs for QFileSystemModel:
Unlike the QDirModel, QFileSystemModel uses a separate thread to populate itse... |
4,391,963 | 4,392,312 | Parsing a template file with C++ | Recently I've been busy with some PHP framework - completely off-topic by the way.
Anyhow, I got specific html/template files I would like to parse with C++ (don't ask me why, it's just because I want to write it in C++). Besides that, it might actually be the first useful thing I would ever write in C++.
Anyway, to ge... | For these type of problems I tend to be inclined towards REGEX. Using either boost::regex or the GNU regex classes or any other library. Identifying those markers and converting them is mostly a regex search and replace thing (with parameters for variable names, values, etc.), and you don't have to write code to actual... |
4,391,980 | 4,392,093 | How to use C# client to get information of clicked GUI element in another app? | Can a C# client record all keyboard and mouse events using hooks and collect information on the clicked GUI element?
Which libary would you use?
Is Spy++ an option or would one need a C++ DLL for that?
| It's better to do it in c++, you should register your hook, then you can create a bridge, but in C# may be Code project article is usefull.
|
4,392,124 | 4,392,150 | c++ Final constant strings | In Java, we can specify a string as final to declare 'constants'. For example
static final String myConst = "Hello";
Is the correct way to do this in c++ like this?
const char * const myConst = "Hello";
I've always seen people do this:
const char * myConst = "Hello";
But, actually, you can change what that pointer p... | const std::string myConst("Hello");
|
4,392,352 | 4,392,379 | argument of type 'void (ClassName::)(QString&)' does not match 'void (ClassName::*)(QString&)' | Im trying to use Qt's qtconcurrentmap to process some images and I'm getting the following error
argument of type 'void (ClassName::)(QString&)' does not match 'void (ClassName::*)(QString&)
I'm also getting
/Library/Frameworks/QtCore.framework/Headers/qtconcurrentmapkernel.h::
In member function 'bool QtConcurrent::... | Two things here. First, the variable listof is declared inside the foreach loop, so it may not be visible at the point of creating future. Second, you should use &ClassName::processImage as the second parameter to QtConcurrent::map().
UPDATE:
Looking at the documentation, it seems you need to write the call to create t... |
4,392,397 | 6,748,112 | Eclipse metrics plugin for C++ | Does anyone know a good metrics plugin for Eclipse that works with C++ ?
I'm looking for lines of code mainly. Thanks.
| There's the open source Eclipse Metrics plugin, but i personally prefer ProjectCodeMeter which integrates with eclipse as external metrics tool.
|
4,392,504 | 4,392,784 | c++ save matrix data into text or XML (better) | I created a file.dat whith this function
int writeData(double* v, int length, FILE* fh)
{
FILE *Stream; //Stream for output.
double*Elem; //Pointer to all the element to save.
assert( fh!=NULL );
Stream = fh;
Elem=(double*)malloc((length+2)*sizeof(double));//Allocate memory to Elem.
if... | Saving the values into text format is easy:
int writeTextData(double* v, int length, FILE* fh)
{
assert( fh!=NULL );
fprintf(fh, "%d\n", length);
for(int i=0;i<length ;i++)
if(fprintf(fh, "%lf ", v[i]) <= 0)
{
printf("Error, can't save the matrix!");
return(0);
}
return(1... |
4,392,546 | 4,392,575 | How to use delete with a variable pointed to by two pointers? | Let say I have a hypothetical pointer declared with new like so:
int* hypothetical_pointer = new int;
and create another hypothetical pointer, with the same value:
int* another_hypothetical_pointer = hypothetical_pointer;
If I were to go about deleting these, which were declared with new, would I have to delete both ... | delete destroys the dynamically allocated object pointed to by the pointer. It doesn't matter if there are one or 100 pointers pointing to that object, you can only destroy an object once.
After you delete hypothetical_pointer;, you cannot use hypothetical_pointer or another_hypothetical_pointer because neither of the... |
4,392,597 | 4,392,641 | Using reinterpret cast to save a struct or class to file | This is something the professor showed us in his scripts. I have not used this method in any code I have written.
Basically, we take a class, or struct, and reinterpret_cast it and save off the entire struct like so:
struct Account
{
Account()
{ }
Account(std::string one, std::string two)
: login_... | It doesn't actually work, but it also does not cause undefined behavior.
In C++ it is legal to reinterpret any object as an array of char, so there is no undefined behavior here.
The results, however, are usually only usable if the class is POD (effectively, if the class is a simple C-style struct) and self-contained (... |
4,392,848 | 4,392,996 | Promoting code reuse for this situation | This is a bit tricky to explain but I will try my best to explain it.
I'm making a Gui API for games and it has Themes.
First I'll explain how Widgets work.
A Button for example, inherits from Widget.
Themes work similarly.
ButtonTheme inherits from WidgetTheme.
Inside each widget class, there is an instance of its co... | A virtual getTheme() (as drewish suggests) but using covariant return types ought to solve your problem without requiring casts.
|
4,392,853 | 4,392,872 | Problem while Debugging a C++ project using Visual Studio 2010 | I'm having two errors everytime I try to debug a simple project in Visual Studio 2010.
Error 1 error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup C:\Users\Fighter\Documents\C++\Point\Point\MSVCRTD.lib(crtexe.obj) Point
Error 2 error LNK1120: 1 unresolved externals C:... | Your program needs a main() function to be valid.
int main(int argc, char* argv[])
{
Point p;
return 0;
}
|
4,393,474 | 4,393,501 | get future time value | #include <time.h>
#include <iostream>
using namespace std;
int main()
{
time_t current = time(0);
cout << ctime(¤t) << endl;
return 0;
}
How can I get the future time, say 1 hour later, from the current time?
| time(2) returns the number of seconds since 1970-01-01 00:00:00 +0000 (UTC). One hour later would be current + 3600.
time_t current = time(0);
time_t inOneHour = current + (60*60); // 60 minutes of 60 sec.
cout << "Now: " << ctime(¤t) << "\n"
<< "In 1 hour: " << ctime(&inOneHour)
<< "\n";
|
4,393,519 | 4,393,531 | String.size() returns incorrect number if there is space in the string | I'm trying to write a program that returns the number of characters in a string. As I was writing my program, I've noticed that there's a bug in the string class.
Say my program is this:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string input;
cout << "Input string: ";
cin >> inp... | That's because your
cin >> input;
only reads up to the first whitespace character.
If you want to get the a whole line, use the following code:
std::string s;
std::getline(std::cin, s);
|
4,393,603 | 4,393,700 | I want to create a Vector to hold classes | I'm very confused about making a vector to hold classes.
If I wanted to hold a bunch of data in a single vector like the example below, then have the data written in a class member function, and able to be called out and used by other functions.
Where do I stick the vector declaration? please help!
#include <vector>
c... | It seems to me that you're stretching the bounds of what a Card object should do. May I suggest the following layout? First defines a single card.
class Card {
public:
Card(int s, int r)
: suit(s), rank(r) {
// Initialize anything else here
}
private:
int suit, rank;
};
Next, define an obje... |
4,393,740 | 4,393,767 | Microsoft Visual C++, compiling small source codes without project file | Well, I've been using Dev-C++ for a while for learning the language [c++], and some stuff wouldn't work properly, like global and local variables. Then I decided to download Microsoft Visual C++ to see how it compared, and it was absolutely great; especially with its aesthetics. One thing that has bothered me, though, ... | I typically make one project for temporary work and just re-use it. If you have a really desperate need to keep around your learning files, then just make one project, add new source files, and exclude all the old ones from the build. There's no need to make a new project for every temporary or learning project.
|
4,393,843 | 4,393,930 | Functor vs template parameters | Is there any performance advantage to be had when using template parameters with static member functions instead of functor-style predicates??
For instance, a functor-style sort interface is typically something like this:
template <typename _Type, typename _Pred>
void sort (
RandomAccessIterator first,
RandomA... | Normal use of sort won't put anything on the heap, for the simple reason that nobody calls malloc or new. If your predicate causes a call to malloc or new, either in its constructor or in the comparison, then you only have yourself to blame...
It's plausible that some stack will be used for the parameter of type _Pred ... |
4,393,924 | 4,394,057 | WinHTTP Error Invalid URL | How do you specify a URL with path for example: http://stackoverflow.com/questions.
The following works but not with the URL specified above in example.
LPCWSTR useragent = L"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12 GTB7.1 ( .NET CLR 3.5.30729)";
DWORD dwSize = 0;
DW... | WinHttpConnect takes only the hostname part. You should pass the rest of the path to WinHttpOpenRequest (the third parameter, pwszObjectName):
WinHttpOpenRequest( hConnect, L"GET", L"/questions", NULL,WINHTTP_NO_REFERER,
WINHTTP_DEFAULT_ACCEPT_TYPES,
WINHTTP_FLAG_SECURE );
|
4,394,430 | 4,394,445 | How to list the functions / symbols contained inside a dynamic library in mac os? | How to list the functions / symbols contained inside a dynamic library in mac os ?
I need to see the list of function exported by a dynamic library.
| Consider How to export symbols from a shared library and How do i find out what all symbols are exported from a shared object?
Also checkout nm http://sourceware.org/binutils/docs-2.16/binutils/nm.html
|
4,394,594 | 4,395,070 | How to find all mutual friendships in large C++ source tree? | In a large C++ source tree, with about 600 or so classes defined, I want to find all pairs of classes where each declares the other a friend.
There are many cases of one class being a friend of another, too many to make it worth wading through a simple grep result.
| You could implement a kind of triple loop here; the algorithm could be as follows:
First loop: find all classes who have friends, and remember the name of the friend and the name of the actual class;
Then run inner loop for all the classes and find a class with the name of the friend from step 1.
Then run another inne... |
4,394,652 | 4,394,675 | How to capture length of sscanf'd string? | I'm parsing a string that follows a predictable pattern:
1 character
an integer (one or more digits)
1 colon
a string, whose length came from #2
For example:
s5:stuff
I can see easily how to parse this with PCRE or the like, but I'd rather stick to plain string ops for the sake of speed.
I know I'll need to do it in... | You can use the %n conversion specifier, which doesn't consume any input - instead, it expects an int * parameter, and writes the number of characters consumed from the input into it:
int consumed;
sscanf(serialized + start, "%d%n", &len, &consumed);
start += consumed;
(But don't forget to check that sscanf() returne... |
4,394,673 | 4,394,703 | Order results by value | I want to loop through a vector to find records with a given ID. The ID is provided by the user. The code below will return all values with the given ID in the order they appear in the vector. How can I order the results by Price, say from lowest to highest?
for(Seek = List.begin() ; Seek !=List.end() ; Seek++) {... | Use the C++ Standard Library sort function with a custom compare should do what you want. I don't know what type Seek is exactly but here is something to get you started.
struct compareSeeks {
bool operator() (const Seek& lhs, const Seek& rhs) { return (lhs.price < rhs.price);}
} mycompare;
// method code here...
so... |
4,394,849 | 4,394,857 | Pass in a reference to a map in C++ | I'm looking to pass in a reference to a map and NOT have map place it somewhere else - Here's what I'm working with:
map<string, Node> _neighbors; // Instance Variable
Node& neighbor(Node& neighbor) {
cout << "HOST: "<< neighbor.host() << " ADDRESS: " << &neighbor << endl;
string key = this->getKey(neighbor);... | You can't store references in an STL container. Containers store objects and references are not objects (in addition, the objects stored in a container must be assignable, and references are not assignable).
You'll want to use a map of pointers:
std::map<std::string, Node*>
Also, beware of ownership issues. You need... |
4,394,880 | 4,394,901 | C++: Read a word from standard input and find out its length? | I want to read a word from standard input and then find out its length in C++. I am currently using:
char str[80];
cout << "Enter your word: " << endl;
scanf("%s", str);
but cannot get the length of the word read in.
How do I do this?
Thanks.
| See how you're using cout to write to the standard output? In a parallel way, in modern C++, we use cin to read from the standard input.
Further, in modern C++, we have a real string type, called std::string, which we use to store strings. It comes from the <string> header, and it can tell us its own length.
Thus:
stri... |
4,394,915 | 4,395,115 | Difficulty calling unmanaged dll from C# | I'm going bleary-eyed trying to figure out why I can't call an external method in an old C++ .dll from my C# application.
Here's the function header:
int __export FAR PASCAL SimplePGPEncryptFile(
HWND hWnd1,
LPSTR InputFileName,
... | TLDR:
string recipientList = (char) 1 + "CA\n\0";
Did some digging based on Jeffora's comment... He's probably right, my first suggestion probably won't buy you anything. I wrote some test code, here's what I found:
When you use this code:
string recipientList = "1CA\n\0";
The bytes you end up with on the inside of ... |
4,395,102 | 4,395,357 | global objects in C++ | In the following C++ code, where is s allocated? Does it use heap, data, bss, or some combination? I'm on a Linux/x86 platform in case that makes a difference. Is there a way to have the g++ compiler show me the layout?
#include <string>
#include <iostream>
using namespace std;
string s;
int main()
{
s = "tes... | The C++ Standard doesn't define where the compiler puts such objects, but on UNIX it's reasonable to think that the string data would be either:
on the BSS, with the default constructor run before main()
on the BSS, with the compiler having determined that all members would be 0 even if the default constructor run, an... |
4,395,289 | 4,395,308 | why i cant instantiate objects inside a switch-case block | my code has 3 classes n_hexa,n_octa,n_bin. The code is here
switch(choice)
{
case 1: cin>>n;
n_hexa nx(n);
break;
case 2: cin>>n;
n_octa no(n);
break;
case 3: cin>>n;
n_bin nb(n);
break;
}
on compiling it gives a message "crosses initialisation of n_hexa" for line of n_octa
| If you want to have temporary objects inside a case, you'll need to scope them properly.
switch(choice)
{
case 1:
{
cin>>n;
n_hexa nx(n);
break;
}
case 2:
{
cin>>n;
n_octa no(n);
break;
}
case 3:
{
cin>>n;
n_bin nb... |
4,395,413 | 4,395,539 | Is C++ and .NET used together in Domains like Banking , Health Care and Telecom | Or I should ask how helpful and benifitial will it be to start with C++
This may seem irelevant but it has some significance for me,may be few others like me.
I just want to know ,How Important is it to Learn C++ , COM and ATL while you are a .NET programmer?
I love programming with .NET and C# .Visual Studio just has ... | The issue (at least for the specific cases you mention, such as shell extensions) with trying to "integrate with a .NET UI" is that you really can't. The reason it's not a good idea to write shell extensions in managed code is that a given process can only load one version of the CLR at any given time. If two shell ext... |
4,395,436 | 4,395,778 | Error with member function template | I am getting compilation error in below code.
class A
{
public:
A()
{
}
~A()
{
}
void func()
{
cout <<"Ha ha ha \n";
}
};
class C
{
public:
C()
{
}
~C()
{
}
template<typename type> func()
{
type t;
t.func();
}
void callme()
{
func<A>();
}
};
| VC6 doesn't support member function templates. You actually have several solutions:
Move func() out of the class definition
template<typename type> void func()
{
type t;
t.func();
}
or rewrite callme()
void callme()
{
A a;
a.func();
}
or use class template
class C
{
public:
template<class T> struct f... |
4,395,577 | 4,395,608 | Why operator () [] -> = must be non-static member? |
Possible Duplicate:
Why are some operators in C++ only allowed to be overloaded as member functions?
Why operator () [] -> = must be non-static member? Why it can't be friend?
| Because you have to call it on an instance of a class. Take for example the -> operator. How would you propose getting a pointer to the class itself? It doesn't make much sense.
|
4,395,744 | 4,395,819 | How to get the latest file from a directory | This is specific to creating a logfiles. When I am connecting to a server using my application, it writes the details to a log file. When the log file reaches to specific size let's say 1MB then I create another file named LOG2.log.
Now While Writing back to log file , there are two or even more log files and I want t... | Your best bet is to rotate log files, which is what gets done in Unix normally (generally via cron.)
One possible implementation is to keep 10 (or however many) old log files around, if your program detects that Log.log is over 1MB then move Log09.log to Log10.log, Log08.log to Log09.log, 7 to 8, 6 to 7, ... 2 to 3, an... |
4,395,991 | 4,395,997 | Null-Terminated string | Which of the following are null-terminated string?
char *str1 = "This is a string.";
char *str2 = "This is a string.\0";
char str3[] = "This is a string.";
const char *str4 = "This is a string.";
const char *str5 = "This is a string.\0";
const char str6[] = "This is a string.";
|
All : a string literal is a null terminated string
str2 and str5 have the particularity of being doubly null-terminated strings
Also :
char *str1 should be const char *str1
char *str2 should be const char *str2
|
4,396,012 | 4,396,030 | "class template" versus "template class" |
Possible Duplicate:
What is the difference between a template class and a class template?
I've seen several C++ gurus rip on people for calling something like
template <typename T>
class SomeClass
{
//...
};
a template class instead of a class template. (Not a huge rip, mind you, but as an indication that some... | According to this page :
Note the distinction between the terms
class template and template class:
Class template
is a template used to generate template classes. You cannot declare
an object of a class template.
Template class
is an instance of a class template.
This MSDN page seems to agree on this defin... |
4,396,050 | 4,396,114 | isupper and islower for wstring | I have a std::wstring and I want to find which character are upper
case and which ones are lowercase. the std::isupper and islower seems
to work on ASCII characters only but I want to be able to find out all
kinds of uppercase and lowercase characters
e.g. á is an "Latin small letter a with acute"
and Á is an "La... | Most implementations are going to provide iswXxx functions, i.e. iswupper and iswlower. The big problem is that the encoding used in wide character strings is undefined and therefore which values are determined as upper and lower case are really up to the target platform. (Note that the iswXxx functions are not in the ... |
4,396,191 | 4,396,791 | GPU Shared Memory Bank Conflict | I am trying to understand how bank conflicts take place.
if i have an array of size 256 in global memory and i have 256 threads in a single Block, and i want to copy the array to shared memory. therefore every thread copies one element.
shared_a[threadIdx.x]=global_a[threadIdx.x]
does this simple action result in a ... | The best way to check this would be to profile your code using the "Compute Visual Profiler"; this comes with the CUDA Toolkit. Also there's a great section in GPU Gems 3 on this - "39.2.3 Avoiding Bank Conflicts".
"When multiple threads in the same warp access the same bank, a bank conflict occurs unless all threads o... |
4,396,194 | 4,396,226 | C++ Library Reference | I'm looking for some sort of API for the C++ Library Reference.
Does any one know of one that lists all (or most) of the functions' interface in the library.
Is there any UML or similar diagram exist for the standard C++ library?
| I've used this one quite a bit in the past. It also has some diagrams.
|
4,396,251 | 4,396,369 | using window messages in qt | i want to handle WM_DEVICECHANGE to detect insertion of usb devices. However i also want to write the gui in qt.
Question
How do i access window messages when using qt on windows?
Thanks
| With QWidget::winEvent.
|
4,396,371 | 4,396,511 | passing in a function to get return value or values | I have a template looking like this:
struct add_node_value_visitor : boost::static_visitor<>
{
add_node_value_visitor(){}
template <typename T>
void operator() ( const T& value) const
{
boost::lexical_cast<std::string, T>(value);
}
};
The problem I have is that the visitor is used inside ... | Something like this?
struct add_node_value_visitor : public boost::static_visitor<>
{
public:
typedef std::function<void(const std::string&)> concat_func_t;
add_node_value_visitor(const concat_func_t& concat) : concat_(concat){}
template <typename T>
void operator() ( const T& value) const
{
... |
4,396,390 | 4,396,419 | Which is the best among GetCountOfObjects, GetNumberOfObjects, and GetObjectCount? | I am a C++ programmer from a non-English country.I am always confused about how to choose one of the following function names:
GetCountOfObjects
GetNumberOfObjects
GetObjectCount
Who can tell me what the subtle differences are between them?
| GetNumberOfObjects probably sounds closest to natural English. GetCountOfObjects sounds slightly awkward. Other than that, there is almost no difference.
My personal style would probably be to use GetNumberOfObjects for a method that just returns a known number, but CountObjects for a method that actually performs the... |
4,396,515 | 4,396,667 | What happens if my Visual C++ custom memory allocator returns a block not properly aligned? | In my Visual C++ program I use a custom operator new that uses malloc() to allocate memory. My custom operator new stores extra data in the first 4 bytes of memory and returns an offset pointer as the beginning of the block (the program is 32 bit):
void* operator new( size_t size )
{
size += sizeof( int );//assu... | On 32 bit windows it will just potentially be slower as the hardware can deal with unaligned data accesses, just more slowly.
On other operating systems / platforms it will likely cause a crash (Or VERY slow performance as the OS catches the unaligned memory access and simulates it for you in some cases)
|
4,396,549 | 4,396,578 | Is this valid C++ code according to standard? | I have this sample code:
struct A
{
bool test() const
{
return false;
}
};
template <typename T = A>
class Test
{
public:
Test(const T& t = T()) : t_(t){}
void f()
{
if(t_.test())
{
//Do something
}
}
private:
const T& t_;
};
int main()
{
... | It won't remain valid. The temporary object will be destroyed after initializing a. At the time you call f you invoke undefined behavior by calling test. Only the following is valid:
// Valid - both temporary objects are alive until after the
// full expression has been evaluated.
Test<>().f();
|
4,396,560 | 4,410,859 | How do you initialize a map which takes a struct as value? | I am using a map as an associative array of IDs -> value, where the value is a struct defining the object:
#include <map>
struct category {
int id;
std::string name;
};
std::map<int, category> categories;
int main() {
categories[1] = {1, "First category"};
categories[2] = {2, "Second ... | In C++ (ISO/IEC 14882:2003), a brace enclosed list of expressions can be used to initialize a variable of aggregate type in the declaration that defines it.
E.g.
struct S { int a; std::string b; };
S x = { 39, "Hello, World\n" };
An aggregate type is an array or a class with no user-declared constructors, no private ... |
4,396,649 | 4,396,674 | Should there be a definition for Base dtor? | Compiler is giving link error and require to provide definition for Base pure virtual destructor.
class Base
{
public:
virtual ~Base() = 0;
};
class Derived : public Base
{
public:
virtual ~Derived(){ std::cout << "Derived dtor"; }
};
int main()
{
Derived d;
}
| Just provide an empty implementation for it (outside the class definition):
Base::~Base() { }
Being pure-virtual just means that you must override the member function in any concrete derived class; it doesn't mean that it cannot have a body. In the case of the destructor, you must supply a body, wether the destructor ... |
4,396,754 | 4,396,836 | Can different versions of DLL be loaded in same application? | My application uses one version of library (a.dll), I am using another DLL(b.dll) which in-turn uses older version of the same library (a.dll) that i use. I am building the application by embedding a manifest file. The DLL i use is also using a embedded manifest file. I am having both the versions of the library in my ... | Your situation is exactly the situation WinSxS is supposed to solve. It should be working.
Either: The manifest files are pointing to the same version, or one of the manifest files is not embedded properly, or
The shared assembly in WinSxS was installed with a configuration policy that automatically redirects requests ... |
4,396,766 | 4,396,914 | QT signal and slot function signature | In this document is explained that signals must have void as a return value, but what about slots? Since signals must not return anything, can I assume it is the same for slots as well?
| Your slots can return a value.
However, if the slot is connected to a signal and called when the signal is emitted, the return value will be ignored.
But the slot is a normal member function and can be called like any other function. In this case, the return value can be used by the caller.
This is said in the document... |
4,396,808 | 4,397,005 | Declaring std::map constants | How to declare std map constants i.e.,
int a[10] = { 1, 2, 3 ,4 };
std::map <int, int> MapType[5] = { };
int main()
{
}
In the about snippet it is possible to give values 1,2,3,4 to integer array a, similarly how to declare some constant MapType values instead of adding values inside main() function.
| UPDATE: with C++11 onwards you can...
std::map<int, int> my_map{ {1, 5}, {2, 15}, {-3, 17} };
...or similar, where each pair of values - e.g. {1, 5} - encodes a key - 1 - and a mapped-to value - 5. The same works for unordered_map (a hash table version) too.
Using just the C++03 Standard routines, consider:
#include... |
4,397,019 | 4,397,228 | Why can't anonymous unions contain members with non-trivial constructors/destructors? | I may be mistaken, but the basic explanation I've found has been that the union can't initialize because it doesn't know which member's constructor to call. The compiler can not automatically generate a constructor for the union.
Why is the user not allowed to define the unions constructor? This would remove said issue... | A bigger reason would be: how would the union know which destructor to call. The language itself doesn't track which member is active in a union.
It seems that C++0x will allow non-trivial types in unions, in which case you'll be forced to implement your own constructor(s) and destructor. (The latter is a little unclea... |
4,397,073 | 4,397,206 | does this struct need a non-default constructor | I have the following struct in C++, and I wondered if I need to define a non-default constructor for it when I use it as follows: boost::shared_ptr<node> p_node = boost:shared_ptr<node>();
struct node
{
std::string name;
std::map<std::string, std::vector<variant> > values; // it is possible that nodes contain a... | "does this POD need a non-default constructor"... what POD? POD's don't contain complex objects like strings and maps. POD stands for plain old data, which is things like doubles and char arrays.
Whether you need a constructor depends on whether you want to make sure all the data is initialised in some sane state. s... |
4,397,156 | 4,397,888 | Global const initializing and difference between constructor in .h or .cpp file | I was wondering why sometimes my global const defined in seperate .h file isn't properly initialized when I need it. Some tests lead me to situation that I can't understand. I don't know how to explain it, so here's the code:
main.cpp
#include <iostream>
#include "class.h"
using namespace std;
A a;
B b;
int main(int ... | Constant objects have internal linkage, so you get a separate copy of CONST in each compilation unit that includes const.h. In this case, you'll get one in main.cpp, and one in class.cpp. You also have your two global objects in main.cpp.
C++ does not define the order in which global objects in different compilation un... |
4,397,208 | 4,399,398 | Renaming a DLL causes the code using it to crash | I have a DLL which is written in native C++. The Visual Studio project name is MyDll and it compiles to a file called MyDll.dll in the output directory.
After compilation, I rename it to MyDll2.dll. (This example seems silly but I have a good reason for renaming it.)
A second project, written in C++/CLI, uses this DLL.... | When building a dll the linker also generates a lib-file which you use to link with in your executable. This lib file contains the dll-name from which the exported functions and data are being imported. So your executable has references to originally name dll in it.
|
4,397,266 | 4,397,534 | Boost.Asio Asynchronous TCP client and multi-threading | My application is a TCP client that closely resembles the Boost.Asio chat client example.
I'm adding a few separate threads that call chat_client::write. Does this mean I would have to add a locking mechanism to do_write or handle_write? is there any recommended method?
| No, you do not need to lock it in that case (in general). The events will only be handled from threads that have an io_service running. If that is only one, no locking is required. post()'ing new messages to an io_service is already thread-safe from multiple calling threads.
In your specific example, you might want to ... |
4,397,345 | 4,398,172 | Redirecting console output of c++ dll used in MFC GUI application | I have a C++ dll reporting lots of useful information via console output using printf or cout. I'm linking this dll to my GUI application written in MFC and want to access its output.
Sounds pretty simple, yeah? Well, I was surprised when after hours of searching internet and implementing several solutions none of them... | You are IIRC getting screwed up by the "Use MFC in a Static Library" setting. Setting/reopening the int (POSIX style) handles won't work because both your DLL and your application are using differenet/separate run time libraries. Solution: Use the "Use MFC in a Shared DLL" setting. Using static run time libraries on Wi... |
4,397,597 | 4,397,622 | Boost::asio sockets - how to disconnect them cleanly? | I am using boost asynchronous sockets for my server application. I've created a disconnect() function that calls boost's close() and then deletes the socket (operator delete).
And it's alright when the function is called from one of the async. handlers, but when I call it from inside my main codebase, the whole applic... | Make sure that the object is alive as long as handlers that may use it exist.
It is likely what one of handlers that uses this socket is called after you call close (as it
reports the error to handler) and then accesses to dead pointer...
Usually, life time handling can be easily done with boost::shared_ptr and boost::... |
4,397,656 | 4,398,063 | problem with QMouseEvent in QRect | OS::win_xp_sp3
Qt::4.6
Is it possible to use QMouseEvent inside QRect?
I have parent widget and inside is some QLabel with text "status unchanged".
Also , inside parent widget is MyRect which is derived from QRect.
Now I want to MouseEvent act only inside this MyRect. For example , if I act on MyRect , text in parent w... | A QRect is neither a QObject nor a QWidget, so it doesn't receive events.
It's just four numbers describing a rectangle (and it doesn't make sense to derive from it).
You can check if a point is the given rect in the mouse event handler of your widget. Like:
void MyLabel::mouseMoveEvent( QMouseEvent* e ) {
if ( !re... |
4,397,690 | 4,397,744 | How do I replicate this C++ enum switch in Java? | I have some C++ code that looks like this:
enum {
FOO = 0x01,
BAR = 0x09;
};
switch (baz) {
case FOO:
{
//...
}
break;
case BAR:
{
//...
}
break;
}
Is it possible to replicate this behaviour in Java?
| Yes, Java has enums:
public enum BazEnum {
FOO(0x01),
BAR(0x09);
private int value;
BazEnum(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public static BazEnum fromValue(int value) {
for (BazEnum curenum : BazEnum.values()) {
... |
4,397,824 | 4,397,881 | Prevent Windows from using the PATH env variable when resolving dll dependencies? | When loading a DLL (either dynamically with LoadLibrary/Ex or statically) is it somehow possible to prevent Windows from using the PATH environment variable to look up the DLL/other DLLs the DLL to be loaded depends upon?
The docs I could find for the Dynamic-Link Library Search Order seem to imply there is no way to p... | For dynamically loaded dlls: the easiest way to control which one is loaded is to not invoke the search logic. The search logic is only invoked if a partial path is supplied - provide a fully qualified path to the dll when calling LoadLibrary and the call will fail if the Dll doesn't exist in that location.
For statica... |
4,397,866 | 4,398,079 | Putting all code of a module behind 1 interface. Good idea or not? | I have several modules (mainly C) that need to be redesigned (using C++). Currently, the main problems are:
many parts of the application rely on the functions of the module
some parts of the application might want to overrule the behavior of the module
I was thinking about the following approach:
redesign the modu... | The only thing I'd worry about is a loss of granularity, partly addressed by suszterpatt previously. Your implementations might end up being rather heavyweight and inflexible. If you're sure that you can predict the future use of the module at this point then the design is probably ok.
It occurs to me that you might wa... |
4,398,069 | 4,398,188 | Need help in understanding the "ABA" problem | I read one article, describing the ABA problem, but there is something, that I can't understand. I have source code, which fails to work and it is similar to the example in article, but I don't understand the problem. Here is the article
http://fara.cs.uni-potsdam.de/~jsg/nucleus/index.php?itemid=6
It says: While the a... |
"head_" and "current" point to the same area in memory, how can head_->next and current->next point to different?
They do not; but the code needs that both head and head->next are stable while the pop method runs - but the CAS only ensures this for head. It silently assumes head->next won't changed without changing h... |
4,398,402 | 4,398,879 | Internationalization in MFC | It's finally (after years of postponing) the time to localize my app in a few other languages other than English.
The first challenge is to design the integration into my C++ / MFC application that has dozens of dialogs and countless strings. I came across two possible alternative implementations:
Compile and deploy l... | I did some long-living MFC projects with different languages.
I strongly recommend the first approach with resource-only DLLs.
The reasons:
(1) If the user does a XCOPY install, he always has the default language (English) in the main executables.
(2) If you don't translate everything (e.g. you're late with your rel... |
4,398,763 | 4,398,796 | c files inside a c++ program | #include <iostream>
#include <string>
#include <vector>
extern "C"{
#include "sql.c"
}
class ReportsSync{
public:
string getQuery();
bool testQuery(string);
};
if i have a cpp file like tis, rather a .h file like this, wud i be able to call functions defines in sql.c... | For #include directives the preprocessor does just a text replacement. It is like you copy all text from sql.c to your source file.
So yes you can call the functions defined in sql.c.
The only thing I know of where care is required is if your C functions take function pointers as parameters to provide a callback. You s... |
4,399,213 | 4,400,791 | reference for QMetaObject::activate | Searching all over the net, I found no references of QMetaObject, except for this. This class has other methods as well. Who knows where to find all details about QMetaObject class?
| You can find all information about QMetaObject by downloading and reading the sources from https://doc.qt.io/. "activate" are 4 private static member functions of QMetaObject declared in qobjectdefs.h and are for "internal index-based signal activation".
|
4,399,328 | 4,399,403 | Windows API W7 JumpList only for .NET? | I'm looking for a way to use JumpLists through plain C or C++ using the Windows API.
The Code Pack seems to be only available for .NET.
Is there anyway to implement them using C/C++ wothout .NET?
I mean how is this possible:
http://www.strixcode.com/q7goodies/
-> C++
http://www.strixcode.com/j7goodies/
-> Java
| Of course it's available for native developers. You were looking in the wrong place.
Here's a link: http://msdn.microsoft.com/en-us/library/dd378460(v=VS.85).aspx#custom_jump_lists
|
4,399,330 | 4,399,378 | C++ basics, vectors, destructors | I'm a little confused about the best practice for how to do this. Say I have a class that for example allocs some memory. I want it to self destruct like an auto but also put it in a vector for some reason unknown.
#include <iostream>
#include <vector>
class Test {
public:
Test();
Test(int a);
virtual ~Test()... | A vector maintains its own storage and copies values into it. Since you did not implement a copy constructor, the default one is used, which just copies the value of the pointer. This pointer is thus deleted twice, once by the local variable destructor and once by the vector. Don't forget the rule of three. You either ... |
4,399,524 | 4,399,840 | boost::function and multiple argument member-function | I have the following definition of a boost::function object:
typedef boost::function<std::string (std::string, std::string)> concat;
I am passing this function as a struct constructor argument:
struct add_node_value_visitor : boost::static_visitor<>
{
typedef boost::function<std::string (std::string, std::string)>... | You need to supply an instance of a Decomposer object, like this:
boost::apply_visitor( add_node_value_visitor( boost::bind( &Decomposer::ConcatValues, yourDecomposer, _1, _2 ), key), var);
|
4,399,618 | 4,427,151 | Perform HTTP POST with libcurl - digest authentication, using curl_easy_send\ curl_easy_recv | I'm trying to write a simple program which uses libcurl to perform HTTP POST using digest authentication.
It works fine when I'm setting the XML buffer that I want to send using appropriate curlopt_easy_setopt calls with CURLOPT_POSTFIELDS and CURLOPT_POSTFIELDSIZE and then calling curl_easy_perform.
However, when I tr... | Well, this is impossible after all.
curl_easy_send and curl_easy_recv are intended for implementing custom protocols.
Thus, what I think is happening is that the normal HTTP protocol handling that libcurl would be doing for curl_easy_perform is not being done at all, so there is no digest\ NTLM\ GSS negotiation avail... |
4,399,700 | 4,399,721 | C style casting and readability in C++ | Yes I know you shouldn't use C style casts in C++, but in some cases I really think it's a lot more readable if you do, compare these two for example:
d = ((double)i * 23.54) / (d + (double)j);
d = (static_cast<double>(i) * 23.54) / (d + static_cast<double>(j));
Which one is more readable?
Now on to my main question.... | The compiler will "create" exactly the same number of doubles. There is no practical difference between casting to and constructing primitive numeric types.
|
4,399,850 | 4,399,946 | C++ Sequential search not finding the last element | So I have an input file. It consists of 40 numbers. The first 20 numbers are input into an array (I've checked this, they're actually there). I then close and re-open the input file. I compare the first 20 numbers in the input file against my array using sequential search. This means they should all be successful. I th... | There are 2 solutions :
length should get 20 as value
length = 20;
or
use "<=" instead of "<" (in this case "length" should be named "lastIndex")
void Search::sequential(ItemType item, bool& found)
{
int index = 0;
while (index <= length && item != list[index])
index++;
found = (index <= length);
}
... |
4,400,446 | 4,400,927 | Can one retrieve the Windows Standby Timer? | Is the Windows standby timer available? How can I retrieve it using c++?
| I think you need CallNtPowerInformation, passing SystemPowerInformation. The returned SYSTEM_POWER_INFORMATION.TimeRemaining ought to be relevant.
|
4,400,610 | 4,400,668 | Resetting Threaded Events - C++ | Let's say that I have a switch statement in my thread function that evaluates for triggered events. Each case is a different event. Is it better to put the call to ResetEvent at the end of the case, or at the beginning? It seems to me that it should go at the end, so that the event cannot be triggered again, until t... | Yes. think that is the way to go. Create a manual reset event (second parameter of CreateEvent API) so that event is not automatically reset after setting it.
|
4,400,665 | 4,401,390 | make GNU gettext work for a MFC App | im trying to add i18n support with gettext on my mfc app, but i found the following problems
1) The ufficial distribution stopped to support MSVC, so i found another build here.
http://gnuwin32.sourceforge.net/packages/gettext.htm
i fixed the include and linker path for the new libraries but when i try to use gettext i... | Try the binaries from ftp.gnome.org; latest gettext build is from 12-Sep-2010 and should AFAIK work fine with MSVC.
http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/
|
4,400,676 | 4,402,183 | Break Point on File Modification or on File Open | I would like to set a break point on file modification for a particular file, or on opening a particular file. This is a file which our software opens and modifies during portions of legacy code. I'm not exactly sure how to approach this problem. One approach I have thought about was to find all of the places where we ... | Put conditional breakpoint to kernel32.CreateFileW and check file name.
Then you will get file handle, so you can put conditional breakpoint to kernel32.CreateFileW and check file handle.
Also you can hook CreateFileW and call __debugbreak() in it.
|
4,400,747 | 4,401,868 | Converting from unsigned long long to float with round to nearest even | I need to write a function that rounds from unsigned long long to float, and the rounding should be toward nearest even.
I cannot just do a C++ type-cast, since AFAIK the standard does not specify the rounding.
I was thinking of using boost::numeric, but i could not find any useful lead after reading the documentation.... | Since you have so many bits in the source that can't be represented in the float and you can't (apparently) rely on the language's conversion, you'll have to do it yourself.
I devised a scheme that may or may not help you. Basically, there are 31 bits to represent positive numbers in a float so I pick up the 31 most si... |
4,401,187 | 4,401,331 | How to make a QT widget update modified properties from its parent widget? | I've got a QWidget that contains several QLineEdits. When I tell the parent QWidget to change its background color
dynamically, I'd like the children (i.e. QLineEdits) to inherit this modification.
Is there an easy (read: one function call) to do this?
If nothing pops up, I think I'll just loop through the children of ... | Generally speaking you don't need to worry about "overhead" in dialogs. Unless you're doing some sort of massive draw operation, UI applications simply don't need a lot of optimizations. Digging down to all children and changing their background is a relatively fast operation compared to the Qt system itself actually... |
4,401,201 | 4,417,943 | What files belong to a build target in CDT managed build? | In CDT's managed builder, how are individual files assigned to build configurations?
Specifically, how can I:
indicate that configuration A has to build and link sources from folders A and B, while configuraion B shall use folders A and C,
include sources (not headers) from a referenced project (or just any external s... |
1st point, assuming there are 3 folders A,B & C containing .cpp files, try this :
select folder C in the 'project explorer' pane, right-click > exclude from build... > check configuration A > ok
select folder B, right-click > exclude from build... > check configuration B > ok
This way configuration A will ignore .cpp... |
4,401,553 | 4,401,580 | Using C++ struct with iPhone app | As I heard it is possible to use C++ Code within an iPhone (Objective C) project, I want to use an encryption library which is written in C++. However, the library uses a C++ type struct which uses a constructor, that I can't get right.
The Struct looks like this:
struct SBlock
{
//Constructors
SBlock(unsigned int l=... | It's definitely possible and the trick is extremely simple: when you are going to use C++ code in your Objective-C++ applications, name your files .mm instead of .m.
So if you have YourViewController.h and YourViewController.m, rename the latter to be YourViewController.mm. It will cause XCODE to use C++ compiler inste... |
4,401,652 | 4,401,751 | throughput control via Sleep | I have this code, the point is that I want to receive no more than 600Kbits/s using a UDP socket, I implemented an algorithm using duration during which we receive and the sleep command....
#if defined (WIN32)
#include <winsock2.h>
typedef int socklen_t;
#elif defined (linux)
#include <sys/types.h>
#include <sys/sock... | If you use non-blocking sockets with select() you can just ignore the data until you're ready to read it. Not reading data will cause the TCP connection to "slow down". However, this way you do not have exact control about the amount of data received. It's just an approximation. All techniques I know of that limit band... |
4,401,929 | 4,401,984 | calling convention and evaluation order | I know that C++ doesn't specify the order in which parameters are passed to a function. But if we write the following code:
void __cdecl func(int a, int b, int c)
{
printf("%d,%d,%d", a,b,c);
}
int main()
{
int i=10;
func(++i, i, ++i);
}
Can we reliably say the output would be 12,11,11 since the __cdecl e... | As per the Standard, there are two things you need to understand and differentiate:
C++ doesn't specify the order in which parameters are passed to a
function (as you said yourself, that is true!)
C++ doesn't specify the order in which the function arguments are evaluated [expr.call].
Now, please note, __cdecl ensure... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.