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 |
|---|---|---|---|---|
2,379,427 | 2,379,522 | multiple inheritance: unexpected result after cast from void * to 2nd base class | My program needs to make use of void* in order to transport data or objects in dynamic invocation situation, so that it can reference data of arbitrary types, even primitive types. However, I recently discovered that the process of down-casting these void* in case of classes with multiple base classes fails and even cr... | It's not a compiler bug - it's what reinterpret_cast does. The DecoratedSquare object will be laid out in memory something like this:
Square
Decorated
DecoratedSquare specific stuff
Converting a pointer to this to void* will give the address of the start of this data, with no knowledge of what type is there. reinterpr... |
2,379,595 | 21,006,138 | Simple libtool alternative? | Being perfectly satisfied with old-style Makefiles, I am looking for a simple alternative to libtool. I do not want to switch to automake, and I keep running into problems with libtool when I try to use it directly. The latest one is 'unsupported hardcode properties', and I am getting fed up with the lack of complete d... | There's jlibtool (which has nothing to do with java).
It's written in C, and can just be bundled with your source.
It was originally an apache project, but whoever was working it there seems to of abandoned it around 2004.
It was taken over by FreeRADIUS project maintainer Alan Dekok, who modernised the code and fixed... |
2,379,634 | 2,379,681 | binary read/write runtime failure | I've looked at binary reading and writing objects in c++ but are having some problems. It "works" but in addition I get a huge output of errors/"info".
What I've done is
Person p2;
std::fstream file;
file.open( filename.c_str(), std::ios::in | std::ios::out | std::ios::binary );
file.seekg(0, std::ios::beg );
file.rea... | Is the name string in the Person struct a character array or a STL string? You can't fill in an STL String by binary reading data over top of it, since the data format is not serializable (contains pointers)
|
2,379,806 | 2,379,903 | Using condition variable in a producer-consumer situation | I'm trying to learn about condition variables and how to use it in a producer-consumer situation. I have a queue where one thread pushes numbers into the queue while another thread popping numbers from the queue. I want to use the condition variable to signal the consuming thread when there is some data placed by the p... | You have to use the same mutex to guard the queue as you use in the condition variable.
This should be all you need:
void consume()
{
while( !bStop )
{
boost::scoped_lock lock( mutexQ);
// Process data
while( messageQ.empty() ) // while - to guard agains spurious wakeups
{
... |
2,379,859 | 2,379,868 | In C++, what does & mean after a function's return type? | In a C++ function like this:
int& getNumber();
what does the & mean? Is it different from:
int getNumber();
| Yes, the int& version returns a reference to an int. The int version returns an int by value.
See the section on references in the C++ FAQ
|
2,379,867 | 2,380,280 | Simulating key press events in Mac OS X | I'm writing an app where I need to simulate key press events on a Mac, given a code that represents each key. It seems I need to use the CGEventCreateKeyboardEvent function to create the event. The problem is that this function needs a Mac keycode, and what I have is a code that represents the specific key. So, for exa... | Here's code to simulate a Cmd-S action:
CGKeyCode inputKeyCode = kVK_ANSI_S;
CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState);
CGEventRef saveCommandDown = CGEventCreateKeyboardEvent(source, inputKeyCode, YES);
CGEventSetFlags(saveCommandDown, kCGEventFlagMaskCommand);
CGEventRef s... |
2,380,071 | 2,380,358 | All things equal what is the fastest way to output data to disk in C++? | I am running simulation code that is largely bound by CPU speed. I am not interested in pushing data in/out to a user interface, simply saving it to disk as it is computed.
What would be the fastest solution that would reduce overhead? iostreams? printf? I have previously read that printf is faster. Will this depen... | My thought is that you are tackling the wrong problem. Why are you writing out vast quantities of text formatted data? If it is because you want it to be human readable, writing a quick browser program to read the data in binary format on the fly - this way the simulation application can quickly write out binary data... |
2,380,143 | 2,380,195 | C++ metaprogramming with templates versus inlining | Is it worth to write code like the following to copy array elements:
#include <iostream>
using namespace std;
template<int START, int N>
struct Repeat {
static void copy (int * x, int * y) {
x[START+N-1] = y[START+N-1];
Repeat<START, N-1>::copy(x,y);
}
};
template<int START>
struct Repeat<START, 0> {
... | That's not better. First of all, it's not really compile time, since you make function calls here. If you are lucky, the compiler will inline these and end up with a loop you could have written yourself with much less amount of code (or just by using std::copy).
|
2,380,153 | 2,380,181 | Finding "dead code" in a large C++ legacy application | I'm currently working on a large and old C++ application that has had many developers before me. There is a lot of "dead code" in the project, classes and functions that aren't used by anyone anymore.
What tools are available for C++ to make a analysis of large code base to detect and refactor dead code? Note: I'm not... | You'll want to use a static analysis tool
StackOverflow: What open source C++ static analysis tools are available?
Wikipedia: List of tools for static code analysis
The main gotcha I've run into is that you have to be careful that any libraries aren't used from somewhere that you don't control/have. If you delete a ... |
2,380,185 | 2,380,521 | Function pointers and unknown number of arguments in C++ | I came across the following weird chunk of code.Imagine you have the following typedef:
typedef int (*MyFunctionPointer)(int param_1, int param_2);
And then , in a function , we are trying to run a function from a DLL in the following way:
LPCWSTR DllFileName; //Path to the dll stored here
LPCSTR _FunctionName; /... | There are three errors I can think of if the expected and used number or type of parameters and calling convention differ:
if the calling convention is different, wrong parameter values will be read
if the function actually expects more parameters than given, random values will be used as parameters (I'll let you imag... |
2,380,258 | 2,380,459 | Crossplatform iPhone / Android code sharing | Simply put: What is the most effective way to share / reuse code between iPhone and Android builds?
The two most common scenarios I think would be:
Blank slate new project, knowing ahead of time there is a large chunk of reusable logic that needs to run on each device.
Existing iPhone code base, porting of C, C++ and ... | In my experience, you can use Android NDK to compile C and C++ , so if you use iPhone Obj-C++ (.mm) bindings for a C++/C engine in the iPhone, and in Android you use Java bindings to the same engine, It should be totally possible.
So C++/C engine ( almost same codebase for Android and iPhone ) + Thin bindings layer = P... |
2,380,307 | 2,412,341 | Why does my std::wofstream write ansi? | I've got wide string and I'm writing it to a wofstream that I opened in out|binary mode. When I look in the resultant file, it's missing every other byte.
I was expecting that when I opened the file in visual studio with the binary editor that I'd see every other byte as a zero, but I'm not seeing the zeros.
Do you kno... | When you write to file using output wide stream, what actually happens is that it converts the wide characters to other 8-bit encoding.
If you were using UTF-8 locale it would convert wide strings to UTF-8 encoded text (but MSVC does not provides UTF-8 locales) so generally it would try to convert to some code-page lik... |
2,380,520 | 2,401,669 | Hosting a VST/DX instrument in C#/C++? | I'm trying to get a read on the effort level involved in building a barebones virtual instrument host in C++ or C# but I haven't been able to get any hard information. Does anybody know any good starter apps, tutorials, helper libraries for this sort of thing?
If it matters, the goal would be to a) accept incoming MIDI... | To capture incoming Midi events use the C# Midi Toolkit (on codeproject.com) by Leslie Sanford or my MIDI.NET library.
VST.NET allows you to load and communicate with managed and unmanaged VST (2.4) plugins. You can also create managed VST plugins with VST.NET that can run in unmanaged Hosts.
There is also a simple C++... |
2,380,574 | 2,380,639 | Are static vars in a method body shared by all instances | class MyClass
{
public:
void method2()
{
static int i;
...
}
};
Will every instance of MyClass share one value i, or will each instance have its own copy?
| static, here, operates as in any regular function.
Which means that i is static within MyClass::method2, so there is one and only one instance of it.
Having one instance of a variable per object is what instance variables are for.
|
2,380,720 | 2,380,738 | Isn't a const variable at namespace scope implicitly static? | I know that static const int x = 42; at namespace scope is equivalent to const int x = 42; because const variables are implicitly static (they must be declared extern to be given external linkage). Every translation unit that includes this declaration gets a local copy of x.
Does this only apply to certain (perhaps in... | In your example, you are creating a pointer to a constant (block of) char rather than creating a constant pointer to a char. Thus, your pointer isn't constant and so isn't implicitly static.
You need to declare x as const char *const A, which creates a constant pointer to a constant (block of) char.
|
2,380,728 | 2,381,064 | Getting the number of trailing 1 bits | Are there any efficient bitwise operations I can do to get the number of set bits that an integer ends with? For example 1110 = 10112 would be two trailing 1 bits. 810 = 10002 would be 0 trailing 1 bits.
Is there a better algorithm for this than a linear search? I'm implementing a randomized skip list and using random ... | Taking the answer from Ignacio Vazquez-Abrams and completing it with the count rather than a table:
b = ~i & (i+1); // this gives a 1 to the left of the trailing 1's
b--; // this gets us just the trailing 1's that need counting
b = (b & 0x55555555) + ((b>>1) & 0x55555555); // 2 bit sums of 1 bit number... |
2,380,747 | 2,380,766 | compiler generated constructors | This is just a quick question to understand correctly what happens when you create a class with a constructor like this:
class A
{
public:
A() {}
};
I know that no default constructor is generated since it is already defined but are copy and assignment constructors generated by the compiler or in other words do ... | Yes. The copy constructor, assignment operator, and destructor are always created regardless of other constructors and operators.
If you want to disable one, what you've got there is perfect. It's quite common too.
|
2,380,803 | 2,380,834 | Is the behavior of return x++; defined? | If I have for example a class with instance method and variables
class Foo
{
...
int x;
int bar() { return x++; }
};
Is the behavior of returning a post-incremented variable defined?
| Yes, it's equivalent to:
int bar()
{
int temp = x;
++x;
return temp;
}
|
2,380,839 | 2,380,885 | Internal compiler error and boost::bind | I'm testing a C++ class with a number of functions that all have basically the same form:
ClassUnderTest t;
DATATYPE data = { 0 };
try
{
t.SomeFunction( &data );
}
catch( const SomeException& e )
{
// log known error
}
catch( ... )
{
// log unknown error
}
Since there's a lot of these, I thought I'd write... | The error is in your code, not in bind. You pass a functor that does not expect any arguments. Instead of your call, do
DoTest< DATATYPE >( boost::bind( &ClassUnderTest::SomeFunction, &t, _1) );
If you omit _1 then bind will create a zero-argument function object, and the member function (which expects a data pointer... |
2,380,854 | 2,381,190 | Massive amount of object creation in C++ | Is there any pattern how to deal with a lot of object instantiations (40k per second) on a mobile device? I need these objects separately and they cannot be combined. A reusage of objects would probably be a solution. Any hints?
| I think you could consider these design patterns:
Object Pool
Factory
Further info
I hope this help you too: Object Pooling for Generic C++ classes
|
2,380,869 | 2,380,979 | How best to test a Mutex implementation? | What is the best way to test an implementation of a mutex is indeed correct? (It is necessary to implement a mutex, reuse is not a viable option)
The best I have come up with is to have many (N) concurrent threads iteratively attempting to access the protected region (I) times, which has a side effect (e.g. update to a... | This reminds me of this question about FIFO semaphore test. In a nutshell my answer was:
Even if you have a specification, maybe it doesn't convey your intention exactly
You can prove that the algorithm fulfills the specification, but not the code (D. Knuth)
Test reveal only the presence of bug, not their absence (Di... |
2,380,957 | 2,381,550 | c++ IPC - d3d hook and directshow capture source | I'm writing an app that will basically be like Fraps, but it will push video frames as a DirectShow Capture Source. This will make it easy to stream games on websites like ustream, justin.tv, etc. I'm wondering what the best way to do the interprocess communication would be. Speed is very important. Right now I have a ... | If you want speed, use shared memory. Combine that with COM for normal communication and you got a standard windows IPC approach.
If you want to wrap it up with a more modern C++ style, take a look at Boost.Interprocess' primitives.
|
2,381,112 | 2,421,271 | SharePoint fails to load a C++ DLL on Windows 2008 | I have a SharePoint DLL that does some licensing things and as part of the code it uses an external C++ DLL to get the serial number of the hardisk.
When I run this application on Windows Server 2003 it works fine, but on Windows Server 2008 the whole site (loaded on load) crashes and resets continually. This is not Wi... | This could be security related:
An important point is that it works in a console app.
In a console app RunWithElevatedPrivileges has no effect since it emulates the app pool user for your worker process, a user that should have no special rights on the box itself.
In contrast a console app runs in context of the logg... |
2,381,119 | 2,381,188 | Parse a string to get the nth field | Im trying to parse the string located in /proc/stat in a linux filesystem using c++
I have lifted and saved the string as a variable in a c++ program
I want to lift individual values from the string. Each value is separated by a space.
I want to know how i would, for example, lift the 15th value from the string.
| std::strings separated by spaces can be automatically parsed from any ostream. Simply throw the entire line into an std::istringstream and parse out the nth string.
std::string tokens;
std::istringstream ss(tokens);
std::string nth;
for (int i = 0; i < 15; ++i)
ss >> nth;
return nth;
|
2,381,719 | 2,381,860 | How to have memfun with two parameters | I want to use this function "EnumWindows(EnumWindowsProc, NULL);".
The EnumWindowsProc is a Callback function:
BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam);
For this callback I want to use a member function of a class.
e.g:
Class MyClass
{
BOOL CALLBACK My_EnumWindowsProc(HWND hwnd, LPARAM lParam);
... | You need to create an Adapter, such as:
#include <windows.h>
#include <iostream>
#include <string>
using namespace std;
class MyCallback
{
public:
MyCallback() : count_(0) {};
static BOOL CALLBACK CallbackAdapter(HWND, LPARAM);
BOOL Callback(HWND);
unsigned count_;
};
BOOL MyCallback::Callback(HWND wn... |
2,381,941 | 2,381,963 | How to get a facet from a std::locale object? | I want to get the numpunct<char> facet for the native locale. I can generate a native locale object by constructing an object with an empty string std::locale native_loc(""), but once I have it how do I get a numpunct from it? The documentation I've found doesn't really show the connection between the two.
| Use use_facet<facet_type>(locale):
std::numpunct<char> const&n = std::use_facet< std::numpunct<char> >(std::locale(""));
|
2,382,122 | 2,382,140 | Long Pointer to Constant Wide String, what's the function of the Long here? | When you have a LPCWSTR, why is it a Long Pointer? There's no Long in it's definition, as far as I know.
Can anybody explain?
| 'Long' is a leftover from Windows-16-bit. In the old days, on DOS and Windows 3.x, most apps were 16 bits and had 16-bit pointers. 32-bit pointers were 'long' and had to be specially declared, and used (in some DOS cases) selectors and not the flat address space.
|
2,382,137 | 2,382,399 | How to unroll a short loop in C++ | I wonder how to get something like this:
Write
copy(a, b, 2, 3)
And then get
a[2] = b[2];
a[3] = b[3];
a[4] = b[4];
I know that C #defines can't be used recursively to get that effect. But I'm using C++, so I suppose that template meta-programming might be appropriate.
I know there is a Boost library for that, but ... | The most straightforward solution to this is to write a loop where the start and end values are known:
for(int i = 2; i <= 4; i++) {
a[i]=b[i];
}
I think this is better than any sort of template/runtime-call mixture: The loop as written is completely clear to the compilers' optimizer, and there are no levels of fun... |
2,382,184 | 2,382,234 | Get a particular text from website | I'm looking for a way if you know the location where to read the text for example say, under a particular category, how would you connect to a website and search & read the text from it?
what steps do i need to follow to learn about that?
| you could use libcurl/cURL for your HTML retrival
|
2,382,834 | 2,382,857 | Discards qualifiers error | For my compsci class, I am implementing a Stack template class, but have run into an odd error:
Stack.h: In member function ‘const T Stack<T>::top() const [with T = int]’:
Stack.cpp:10: error: passing ‘const Stack<int>’ as ‘this’ argument of ‘void Stack<T>::checkElements() [with T = int]’ discards qualifiers
Stack<T>... | Your checkElements() function is not marked as const so you can't call it on const qualified objects.
top(), however is const qualified so in top(), this is a pointer to a const Stack (even if the Stack instance on which top() was called happens to be non-const), so you can't call checkElements() which always requires ... |
2,382,871 | 2,389,681 | Lightweight alternatives to CDT for C++ editing in eclipse | For a few years now, I've been using Eclipse as my all-purpose file editor, regardless of the language I use (which mainly includes C++, Matlab and python, with some XML thrown in for fun).
However, I recently got a new machine with more a recent Eclipse, and the wonderful Colorer plugin, which I previously used, cras... | I've finally figured out a work-around to my performance issue.
There is a "scalability" mode in CDT that kicks in when your file is above a certain number of lines (under Preferences-C/C++-Editor-Scalability). By changing the default size to 1, I can disabled the "editor live parsing" that seems to be causing the pro... |
2,382,930 | 2,382,972 | C++: allocate block of T without calling constructor | I don't want constructor called. I am using placement new.
I just want to allocate a block of T.
My standard approach is:
T* data = malloc(sizeof(T) * num);
however, I don't know if (data+i) is T-aligned. Furthermore, I don't know if this is the right "C++" way.
How should I allocate a block of T without calling its c... | Firstly, you are not allocating a "block of T*". You are allocating a "block of T".
Secondly, if your T has non-trivial constructor, then until elements are constructed, your block is not really a "block of T", but rather a block of raw memory. There's no point in involving T here at all (except for calculating size). ... |
2,383,109 | 2,389,350 | Passing c++ map data to c# | I have a map (enum, vector< double >) in c++ code that I want to access from a c# application. This is legacy code, so I'm limited to using COM objects to pass information. Currently we pass in one enum at a time to c++, and get back one vector at a time as a SAFEARRAY.
I tried passing in a SAFEARRAY of enums, and ret... | I found how to do it. Instead of using a SAFEARRAY of SAFEARRAYs, I use a SAFEARRAY of VARIANTs. I turn each vector of doubles into a SAFEARRAY, convert the SAFEARRAY to a VARIANT, and then put the VARIANT into a SAFEARRAY that I return to c#. It produces the jagged array that I want.
|
2,383,334 | 2,383,386 | Find out the number of digits of min/max values of an integral type at compile time | Is there a way to find out the number of digits of min/max values of an integral type at compile time so that it's suitable to be placed as a template parameter?
Ideally, there will be an existing solution in, for example, Boost MPL. Failing that I'm looking for some pointers for a hand-coded solution.
| Is this what you are looking for?
std::numeric_limits<T>::digits10
Number of digits (in decimal base) that can be represented without change.
|
2,383,377 | 2,383,430 | find an item in a stl set in c++ | I am trying to find an author in a set, and i am having problems doing so.
in the library.cpp is where i am adding the information from main()
#include "Library.h"
#include "book.h"
#include "cd.h"
#include "dvd.h"
#include <iostream>
// general functions
ItemSet allBooks;
ItemSet allCDS;
ItemSet allDVDs;
ItemSe... | How about checking to see whether the author is in allBooksByAuthor before inserting them?
allBooksByAuthor[author] = obj;
will replace the ItemSet* which is already in there. So, your ItemSet will only ever have one Item* in it. How about something more like
ItemSetMap::iterator authorsBooks = allBooksByAuthor.find(a... |
2,383,438 | 2,383,474 | How do I return a char* array from a clr assembly? | I have a simple managed C++ assembly which I am providing unmanaged wrappers for some static methods I have in a C# assembly. One of these methods returns a string which I have converted to a "const char*" type in the C++ assembly. The trouble I am having is that when I load this dll from an unmanaged source, I get bad... | wprintf with a %s format specifier will interpret your first parameter as a "const wchar_t*", while you're passing a "const char*" to it. Try to use wchar_t in your GetValue function.
|
2,383,520 | 2,383,566 | On Mac OS X in C++ on a 64-bit CPU, is there a type that is 64 bits? | I can't use "long long"; what should I be using?
| Assuming Snow Leopard (Mac OS X 10.6.2 - Intel), then 'long' is 64-bits with the default compiler.
Specify 'g++ -m64' and it will likely be 64-bits on earlier versions too.
1 = sizeof(char)
1 = sizeof(unsigned char)
2 = sizeof(short)
2 = sizeof(unsigned short)
4 = sizeof(int)
4 = sizeof(unsigned int)
8 = sizeof(... |
2,383,554 | 2,383,582 | A combined function for fprintf and write in c/c++ | In C/C++, there is a 'write() function which let me write to either file or a socket, I just pass in the file descriptor accordingly). And there is a fprintf() which allow me to do fprintf (myFile, "hello %d", name); but it only works for file.
Is there any api which allows me to do both?
i.e. able to let me do print ... | You can use sprintf or snprintf to print to a char * buffer, and then use write. To get a file descriptor from a FILE * variable, you can use fileno. There is no portable way to go from a file descriptor to a FILE *, though: you can portably to use fdopen to associate a FILE * with a valid file descriptor.
In additio... |
2,383,622 | 2,383,636 | Indexing my while loop with count parameter in an array | My function takes an array of ifstream ofjects and the number of ifstream objects as seen below:
void MergeAndDisplay(ifstream files[], size_t count)
My problem is I want to use a while loop to read from the file(s) as long as one of them is open. When I get to eof, I close the file. So I thought I could do somethin... | You will have to compute the logic of "is any file in this set open" separately. I suggest making it its own function so that the while loop can be clean and natural, e.g.
bool isAnyOpen(ifstream files[], size_t count) {
for (size_t i = 0; i < count; ++i) {
if (files[i].is_open()) return true;
}
return false;... |
2,383,699 | 2,383,722 | error C2593: 'operator +' is ambiguous | If I have the following files, I get this error (c2593 in VC9).
If I un-comment the prototype in main.cpp, the error disappears. I need to maintain the same functionality while keeping the class out of main.cpp. How can I do that?
Thanks.
main.cpp:
#include "number.h"
//const Number operator + (const Number & lhs, con... | You never declare operator + in number.h, you only define it in number.cpp - therefore, when you include number.h in main.cpp, it doesn't know where to go to find operator +.
You must put the declaration of operator + in number.h, outside of the class, then define it in number.cpp
|
2,384,020 | 2,384,234 | What is the purpose of Windows style flags like WS_TILED and WS_ICONIC that are just renaming of others? (Windows/C++) | I was looking at the various windows styles flags, and I noticed that a few flags are defined as such:
#define WS_TILED WS_OVERLAPPED
#define WS_ICONIC WS_MINIMIZE
#define WS_SIZEBOX WS_THICKFRAME
#define WS_TILEDWINDOW WS_OVERLAPPEDWINDOW
What is the purpose of defining new flags th... | Its purpose is backwards compatibility. WS_TILED and WS_ICONIC probably date back to Windows version 1.
One of Microsoft's great burdens, once they put a #define or function in an SDK header file, they can never delete it again.
|
2,384,095 | 2,384,106 | c++ visual studio 2008 issue with two projects in one solution | I have a solution created using visual studio 2008 named, "Solution", and i have two projects in that solution, project "A" and project "B". when i do a thing like below it shows fatal errors in the bottom. I have given in project A->properties->Additional include Directries as ../B
project B
B.h
#include <iostream>
u... | It doesn't look like you are exporting class B out of project B. So project A sees the declaration of class B but can't find its implementation. What does project B build?
|
2,384,107 | 2,384,187 | How does this template magic determine array parameter size? | In the following code
#include<iostream>
template<typename T,size_t N>
void cal_size(T (&a)[N])
{
std::cout<<"size of array is: "<<N<<std::endl;
}
int main()
{
int a[]={1,2,3,4,5,6};
int b[]={1};
cal_size(a);
cal_size(b);
}
As expected the size of both the arrays gets printed. But ... | N does not get "initialized" to anything. It is not a variable. It is not an object. N is a compile-time constant. N only exists during compilation. The value of N as well as the actual T is determined by the process called template argument deduction. Both T and N are deduced from the actual type of the argument you p... |
2,384,137 | 2,384,154 | Is the following std::vector code valid? | std::vector<Foo> vec;
Foo foo(...);
assert(vec.size() == 0);
vec.reserve(100); // I've reserved 100 elems
vec[50] = foo; // but I haven't initialized any of them
// so am I assigning into uninitialized memory?
Is the above code safe?
| It's not valid. The vector has no elements, so you cannot access any element of them. You just reserved space for 100 elements (which means that it's guaranteed that no reallocation happens until over 100 elements have been inserted).
The fact is that you cannot resize the vector without also initializing the elements... |
2,384,276 | 2,384,465 | Backslash in the end of comment lines in C/C++ | Does your editor/ide highlight that a++; in this C/C++ code as part of a comment?
int a=1;
//some comment \
a++;
printf("%d\n",a);
And what about this?
int a=1;
//some comment ??/
a++;
printf("%d\n",a);
| emacs 22.3.1: No to both, sadly
|
2,384,360 | 2,384,365 | How can I initialize a reference attribute in my class | I have a class which has a private attribute which is a reference to another class:
class A {
public:
A();
A(B& anotherB);
private:
B& bRef;
}
In my A(B& anotherB), I can do this:
A::A(B& anotherB)
: bRef(anotherB) {
}
But what about A()? I tried this:
A::A()
: bRef(B()) {}
But I get this error... | You have to have a real instance to initialize it to. Saying : bRef(B()) creates a temporary which is immediately destroyed, thus your reference would be to an object that no longer exists, thus the compiler error.
You don't need to initialize it unless you're making some decision based on it not being initialized. I... |
2,384,405 | 2,387,502 | What can cause Phong specular shading to produce gamut overflows? | I am currently implementing a basic raytracer in c++. Works pretty well so far, matte materials (with ambient and diffuse brdf) work as expected so far.
Adding specular highlights would result in the full Phong Model and that's exactly what i tried to do.
Unfortunately, i encounter gamut overflow, with all kinds of val... | The solution to the problem is that you have to unify the wo vector (in Phong::shade).
|
2,384,558 | 2,384,579 | C++ inline class definition and object initialisation | I've just come across the following code:
#include <iostream>
static class Foo
{
public:
Foo()
{
std::cout << "HELLO" << std::endl;
}
void foo()
{
std::cout << "in foo" << std::endl;
}
}
blah;
int main()
{
std::cout << "exiting" << std::endl;
blah.foo();
retur... | It's quite standard to define a class (or struct, perfectly equivalent except that the default is public instead of private) and declare a variable of its type (or pointer to such a variable, etc) -- it was OK in C (with struct, but as I already mentioned C++'s class, save for public vs private, is the same thing as st... |
2,384,562 | 2,384,611 | Double UDP socket binding in Linux | In C++, when I run (red alert! pseudo-code)
bind(s1, <local address:port1234>)
bind(s2, <local address:port1234>)
on two different UDP sockets (s1 and s2 each created with a call to socket()) I get problems. In Linux (Ubuntu), the double binding seems to be fine. In Windows, however, the double binding fails, and the ... | Please see bind and setsockopt. Unless you have invoked setsockopt with SO_REUSEADDR, then your invocation of bind with the same address should result in failure with EADDRINUSE.
|
2,384,637 | 2,384,668 | const reference to temporary and copying - C++ | Please consider the following code,
struct foo
{
foo()
{
std::cout << "Constructing!" << std::endl;
}
foo(const foo& f)
{
std::cout << "Copy constructing!" << std::endl;
}
~foo()
{
std::cout << "Destructing.." << std::endl;
}
};
foo get()
{
foo f;
r... | Your MSVC build has no optimizations on. Turn them on, you'll get identical output for both.
GCC is merely performing, by default, RVO on your temporary. It's basically doing:
const foo& f = foo();
MSVC is not. It's making the foo in the function, copying it to the outside the function (ergo the copy-constructor call)... |
2,384,739 | 2,384,914 | Template class, static function compile error c++ | I have the following function defined inside my linked list class. The declaration in the header file looks like this:
template <typename T>
class RingBuffer
{
...//stuff
static BLink * NewLink (const T&); // allocator
};
BLink is a "link" class within the RingBuffer class. The following implementation code:
tem... | The problem here is that you are referring to a nested dependent type name (i.e. BLink is nested inside RingBuffer which is dependent on a template parameter)
You need to help your compiler a little in this case by stating that RingBuffer<T>::BLink is an actual type name. You do this by using the typename keyword.
temp... |
2,384,761 | 2,384,857 | C++: Cannot instantiate a pointer directly | This is an SDL problem, however I have the strong feeling that the problem I came across is not related to SDL, but more to C++ / pointers in general.
To make a long story short, this code doesn't work (edited to show what I really did):
player->picture = IMG_Load("player");
SDL_BlitSurface(player->picture, NULL, scree... | I am so stupid. Turns out like I forgot the file extension ".png" every time I tried to store the surface in Player::picture, and conveniently remembered to add it every time I stired it in an SDL_Surface declared in main.cpp.
I had the feeling I was overlooking something really simple here, but this is just embarassin... |
2,384,782 | 2,388,726 | Printf used in unfamiliar fashion | I found this line of code when upgrading a C++ Builder project to RAD Studio 2009:
mProcessLength->Text.printf("%d",mStreamLength);
It doesn't compile in 2009, however what is the intent of this line and what is a better equivalent? Given that mProcessLength->Text is now a wchar_t*.
| I suspect that you are getting these errors:
E2034 Cannot convert 'const char *' to 'const wchar_t *'
E2342 Type mismatch in parameter 'format' (wanted 'const wchar_t *', got 'const char *')
It's the parameters you are passing to printf that are mismatched.
Changing it to:
mProcessLength->Text.printf(L"%d",mStreamLeng... |
2,384,933 | 2,385,008 | Program configuration data in Unix/Linux | What is recommended way to keep a user configuration data in Unix/Linux?
My programming language is C++. Configuration data will be kept in XML/text/binary format, I have no problem with handling such files. I want to know where can I keep them. For example, in the Windows OS configuration data may be kept in the Regis... | The concept of the registry is peculiar to Windows, and Microsoft once admitted to it being ill-conceived (see this, this, this, this (see #2), and this).
In Unix and Linux, configuration for system-wide programs is in /etc or maybe an application-specific subdirectory.
Per user configuration data are kept in the user'... |
2,385,599 | 2,385,772 | Visual C++ Tail Call Optimization | According to answers to that question:
Which, if any, C++ compilers do tail-recursion optimization?
it seems, that compiler should do tail-recursion optimization.
But I've tried proposed options and it seems that compiler can't do this optimization in case of template functions. Could it be fixed somehow?
| I don't use the MS compilers, but GCC can certainly do tail-recursion optimisation for templates. Given this function:
template <typename T>
T f( T t ) {
cout << t << endl;
if ( t == 0 ) {
return t;
}
return f( t - 1 );
}
The code produced is:
5 T f( T t ) {
6 cout << t << endl;
- 0... |
2,385,673 | 2,386,528 | Setting up cURL library for MSVS | I'm trying to write a simple curl program to retrieve the web page in VC++ 8.0.
#include <stdio.h>
#include <curl.h>
int main(void)
{
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "curl.haxx.se");
res = curl_easy_perform(curl);
/* alw... | if you run it outside of debug mode, does it work as expected? or does the same error occur?
if it doesn't work outside of debug mode, your application was not able to locate the dll.
another question, are you tring to compile libcurl from sources along with your project, or are you using it as an external library?
if... |
2,385,690 | 2,386,586 | Sorting only using the less-than operator compared to a trivalue compare function | In C++/STL sorting is done by using only the less-than operator. Altough I have no idea how the sorting algorithms are actually implemented, I assume that the other operations are created implicite:
a > b *equals* b < a == true
a == b *equals* !(a < b) && !(b < a)
Compared to using a trivalue* compare function, like f... | In a sense the other two are implicit, but more accurate would be to say that a comparison sort doesn't actually need a tri-valued comparator, and C++'s sorts are implemented in a way which doesn't use one in order to minimise the behaviour required of the comparator.
It would be wrong for std::sort to define and excl... |
2,385,698 | 2,385,974 | Why does the following code not generate a warning in MSVC | I have a section of code that can be summarised as follows;
void MyFunc()
{
int x;
'
'
x;
'
'
}
I would have thought that simply referencing a variable, without modifying it in anyway or using its value in anyway should generate a warning. In VS2003 it does neither, and it I need lint to pick it up.
I realise ... | You need to use a better compiler :-) Compiled with the -Wall and -pedantic flags, the GCC C++ compiler given this code:
int main() {
int x = 0;
x;
}
produces this diagnostic:
ma.cpp:3: warning: statement has no effect
|
2,385,744 | 2,385,769 | Simplest way to validate a GPS string in C++? | I have some MET data I want to validate which would look something like these:
char validBuffer[] = {"N51374114W1160437"};
char invalidBuffer[] = {"bad data\n"};
char emptyBuffer[] = {""};
I've tried a simple sscanf, but that failed:
int _tmain(int argc, _TCHAR* argv[])
{
char validBuffer[] = {"N51374114W1160437"... | How about using Regular expressions from TR1?
|
2,385,913 | 3,244,508 | How to set timeout in mysql c++ connector | I am using c++ connector to connect to MySQL server. When server is offline or in sleep,the statement execute method takes a while to detect the connection problem.
Is there a method or variable to control the waiting timeout period in client?
Regards
Devara Gudda
| You can use the mysql_options function to set the client timeout. Full details here... http://dev.mysql.com/doc/refman/5.0/en/mysql-options.html
|
2,386,067 | 2,432,260 | C++ function calling from C# application. Attempted to read or write protected memory | The problem below is ralated to my previous question
Converting static link library to dynamic dll
My first step was to develop a dll, that was done. (Thanks John Knoeller prakash. Your input was very helpful)
Now when i call the function in the dll from my c# application i get the error
"Attempted to read or write pr... | The 4th parameter need to be passed using out mode instead of ref. That solved the problem.
|
2,386,161 | 2,386,233 | Why autoconf isn't detecting boost properly? | I am using autoconf to detect boost libraries, with the support of the autoconf-archive macros and they work fine with system-wide boost libraries, but fail if I manually compile boost in my home directory:
sb@stephane:~/devel/spectra2$ ./configure --with-boost=/home/sb/local/
checking for a BSD-compatible install... /... | Since boost-1.39 libboost_filesystem depends on libboost_system. Before 1.39 you could only link to boost_filesystem, in later versions you have to link to both of them.
Maybe it has something to do with your error.
|
2,386,224 | 2,386,262 | c++ transform with pair get Segmentation fault | This code works:
class Test
{
public:
Test(string name) : _name(name) {};
bool operator()() { cout << "hello " << _name << endl; return true; }
string name() { return _name; }
private:
string _name;
};
pair<string, bool>
inline execute_test(Test* t) {
return pair<string, bool>(t->name(), (*t)());
}
int main... | That is because transform is expecting results object to have the required memory allocated i.e. it is expecting results.size() is atleast as big as tests.size(). If you want to push_back operation to be performed on the results then you should use std::back_inserter(results) as the third argument. Otherwise, when tran... |
2,386,231 | 2,386,279 | Under what circumstances must I provide, assignment operator, copy constructor and destructor for my C++ class? | Say I've got a class where the sole data member is something like std::string or std::vector. Do I need to provide a Copy Constructor, Destructor and Assignment Operator?
| In case your class contains only vector/string objects as its data members, you don't need to implement these. The C++ STL classes (like vector, string) have their own copy ctor, overloaded assignment operator and destructor.
But in case if your class allocates memory dynamically in the constructor then a naive shallow... |
2,386,492 | 2,386,535 | How to remove smart pointers from a cache when there are no more references? | I've been trying to use smart pointers to upgrade an existing app, and I'm trying to overcome a puzzle. In my app I have a cache of objects, for example lets call them books. Now this cache of books are requested by ID and if they're in the cache they are returned, if not the object is requested from an external system... | I never used boost::intrusive smart pointers, but if you would use shared_ptr smart pointers, you could use weak_ptr objects for your cache.
Those weak_ptr pointers do not count as a reference when the system decides to free their memory, but can be used to retrieve a shared_ptr as long as the object has not been delet... |
2,386,552 | 2,976,704 | Error yaml-cpp compile in RAD Studio 2010 | I can't compile yaml-cpp in RAD Studio 2010. I have error in nodeutil.h
template <typename T, typename U>
struct is_same_type {
enum { value = false };
};
template <typename T>
struct is_same_type<T, T> {
enum { value = true };
};
template <typename T, bool check>
struct is_index_type_with_check {
enum { value = fals... | Trying out your code with CodeBlocks, the problems showed exactly vice versa. This means, that my code compiles with
template <> struct is_index_type_with_check<std::size_t, false>
and fails with
template <> struct is_index_type_with_check<std::size_t, true>
in line 24.
The problem seems to be, which types compilers ... |
2,386,671 | 2,386,730 | Help with using Xcode | So, I'm using Xcode to program with C++. I want to access the C++ tool but I'm having this problem.
This is what it looks like when opening a new project. Only for me, I don't have the 'Command Line Utility' option at the end.
alt text http://img.skitch.com/20100305-gsab76ef7bkx5ihwwj94cui39t.jpg
How can I get the 'Co... | If you're on a reasonably current version of Xcode (e.g. 3.2.2) then the selection process is slightly different - you need Application -> Command Line Tool and then select C++ stdc++ from the popup menu.
|
2,386,772 | 2,386,882 | What is the difference between float and double? | I've read about the difference between double precision and single precision. However, in most cases, float and double seem to be interchangeable, i.e. using one or the other does not seem to affect the results. Is this really the case? When are floats and doubles interchangeable? What are the differences between them?... | Huge difference.
As the name implies, a double has 2x the precision of float[1]. In general a double has 15 decimal digits of precision, while float has 7.
Here's how the number of digits are calculated:
double has 52 mantissa bits + 1 hidden bit: log(253)÷log(10) = 15.95 digits
float has 23 mantissa bits + 1 hidden b... |
2,386,896 | 2,386,948 | Retrieve time from the internet (bypassing PC clock)? | For my MFC/C++ unmanaged time-limited software needs, I'd like to get a GMT/UTC time-stamp from the internet (instead of relying on the PC clock time that can be easily changed).
I already though about parsing the line "Current UTC"... line from http://www.timeanddate.com/worldclock/ (I think port 80 is more likely to ... | Looks feasible and this is widely done.
Scraping of timeanddate.com can break if the site decides to change its HTML. Even a slight change in the HTML can break your scraper.
I would suggest you use a web service like earthtools. You'll have to pass the necessary arguments(latitude and longitude etc) in the URL and t... |
2,387,083 | 2,387,089 | Where should you put global constants in a C++ program? | Where would you put global constants in a C++ application? For example would you put them in a class? In a struct?
| I would use a namespace for global constants which are not very strongly associated with a single class. In the latter case, I would put them in that class.
Really global (application-level) constants should be in the application's namespace (provided your application is inside it's own namespace, as it should be). For... |
2,387,173 | 2,421,178 | Open Source FIX Client Simulator | I want test a FIX gateway for our company and was wondering if anything in opensource already exists that I can use or perhaps leverage to complete this task.
I am currently looking at QuickFix but I am not sure if it has a client that can be use against any standard FIX gateway.
Also links to any learning material t... | QuickFIXengine code comes with couple of examples, see http://www.quickfixengine.org/quickfix/doc/html/examples.html
You probably want tradeclient for sending messages. It is a command line tool that will send FIX messages to server.
You can use the ordermatch example to start up simple FIX server which will cross orde... |
2,387,386 | 2,387,414 | Using C++ hex and cin | If you have the following code:
cout << hex << 10;
The output is 'a', which means the decimal 10 is converted into its hexadecimal value.
However, in the code below...
int n;
cin >> hex >> n;
cout << n << endl;
When input is 12, the output becomes 18. Can anyone explain the details of the conversion? How did it becam... | The hex manipulator only controls how a value is read - it is always stored using the same internal binary representation. There is no way for a variable to "remember" that it was input in hex.
|
2,387,403 | 2,536,571 | STLport crash (race condition, Darwin only?) | When I run STLport on Darwin I get a strange crash. (Haven't seen it anywhere else than on Mac, but exactly same thing crash on both i686 and PowerPC.) This is what it looks like in gdb:
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: 13 at address: 0x0000000000000000
[Switching to process 2109... | This problem was caused by an unrelated crash bug, causing memory overwrites leading to an STLport crash in my case.
|
2,387,484 | 2,389,369 | ComCtl32.dll Version 6 with Qt | I'm trying to implement a balloon tip. By following the instructions on this page:
http://msdn.microsoft.com/en-us/library/bb760252%28VS.85%29.aspx
I managed to implement the balloon, but the balloon is not using the appropriate theme under Win7. I read somewhere else that for the balloon to use the right visual style,... | I've blogged about this.
|
2,387,647 | 2,387,674 | Exception specification when overriding a virtual function | Consider the following code:
class A
{
public:
virtual void f() throw ( int ) { }
};
class B: public A
{
public:
void f() throw ( int, double ) { }
};
When compiled, it says that derived class B has a looser throw specifier compared to A. What is the importance of this? If we try to exchange their exception ... |
Don't use exception specifications in C++. It's very counter-intuitive compared to, say, Java's ones.
Having a wider specification in the derived class breaks LSP (Liskov Substitution Principle).
To expand on point 2: A's callers expect that only int comes out, but if you use a B (which, because it's publicly derived... |
2,387,914 | 2,388,027 | Basic questions about RAII, STL pop, and PIMPL | While reading proggit today, I came upon this comment in a post about how the top places in the Google Ai challenge were taken by C++. User reventlov declares
The biggest problem I have with C++ is that it's waaay too easy to think that you're a "C++ programmer" without really understanding all the things you need to ... |
A good example where RAII is crucial but sometimes forgotten is when locking a mutex. If you have a section of code that locks a mutex, performs operations, then unlocks it, if the operations throw an exception or otherwise cause the thread to die, the mutex remains locked. This is why there are several scoped lock ... |
2,388,102 | 2,397,437 | c++ recursive mpl::equal problem? | i need an mpl::equal like procedure that supports recursion on types.
namespace mpl = boost::mpl;
BOOST_MPL_ASSERT(( mpl::equal<
mpl::vector<int, char>,
typename mpl::push_back<mpl::vector<int>, char>::type > )); // OK
the above compiles fine, however if i use it in mpl::transform or mpl::fold, visual studio 201... | mpl::transform doesn't create mpl::vector<>'s in your case but mpl::vector2<>'s. These are different types, even if they are semantically equivalent. So if you write:
typedef mpl::vector2<
mpl::vector2<int, char>, mpl::vector2<char, char>
> type_1;
typedef mpl::transform<
mpl::vector<mpl::vector<int>, mpl::... |
2,388,118 | 2,388,161 | Opening multiple files in C++ | I have this code to open multiple files one at a time that is given at the command line, and then if it cannot open one of the files, it closes all the files and exits.
/* Opens an array of files and returns a pointer to the first
* element (the first file).
*/
ifstream *OpenFiles(char * const fileNames[], size_t ... | You need to exit(EXIT_FAILURE) after you delete[] fileObj in the loop, otherwise you'll simply crash on the next iteration. That may be what warning 449 is telling you.
Other than that, the code looks fine. If you want it to compile without those warnings, though, you could turn the inner loop into a standard for-loop ... |
2,388,224 | 2,388,231 | Where is the memory for a local C++ vector allocated? | I noticed that the memory for vector is allocated dynamically. So for a local vector, where does the memory is allocated?
f(){
vector<int> vi;
}
| The vector is allocated on the stack (28 bytes on my system). The vector contents are allocated on the heap.
|
2,388,296 | 2,389,300 | Is Qt 4.6 compiled with Cocoa by default on Snow Leopard? | At work, I was told to configure and build Qt 4.6 with the cocoa flag
./configure -cocoa
Instead I just ran configure without any flags on my Mac OS X 10.6 machine.
Does that mean I have to reconfigure or is cocoa linked by default in Snow Leopard?
Alternatively, how can I check if my Qt build is linked against cocoa... | According to this post -cocoa is only default for 64 bit builds in 4.6 - you have to either supply the -cocoa or -arch x86_64.
If you want to make sure ask configure for its options and look for the defaults.
|
2,388,402 | 2,389,474 | C++ - Load all filename + count the number of files in a current directory + filter file extension | I want to count the number of file in the current directory as well as load all file names in the array. If possible, I want to know how to filter file extension also
| Link the following program with -lboost_filesystem
#include <iostream>
#include <string>
#include <vector>
#include <boost/algorithm/string/case_conv.hpp>
#include <boost/filesystem.hpp>
int main( int argc, char ** argv )
{
std::string ext = ".jpg";
std::vector<std::string> files;
for ( boost::filesystem::dir... |
2,388,625 | 2,388,740 | Need help understanding _set_security_error_handler() | So , I've been reading this article:
http://msdn.microsoft.com/en-us/library/aa290051%28VS.71%29.aspx
And I would like to define my custom handler.However, I'm not sure I understand the mechanics well.What happens after a call is made to the user-defined function ( e.g. the argument of _set_security_error_handler() ) ?... | The documentation states:
"After handling a buffer overrun, you should terminate the thread or exit the process because the thread's stack is corrupted"
Given this statement, it would seem that you could indeed simply kill the thread. However, you are correct to ask what problems this could cause. The docs for Termin... |
2,388,643 | 2,388,929 | Downcasting non-template base class to templated derived class: is it possible? | I'm implementing an event system for a game. It uses an event queue, and a data structure to hold all registered event handlers for a given event type. It works fine so far registering handlers, but when it comes to unregistering them (something that will take place when a game object is destroyed, for instance) I'm ha... | In general when closing templates, you need to make sure that > are separated by spaces so the compiler doesn't parse them as a right-shift operator.
Here you're trying to static cast a reference to a non-reference, which even if it worked could invoke object slicing. You need to static cast to a derived reference.
boo... |
2,389,013 | 2,783,364 | QIcon inside combobox | I want to include a "remove" icon on entries in my QComboBox, but I am having trouble catching the mouse press event. I've tried to catch it on the combobox, and I've tried reimplemting the QIcon class to catch the mousepress there. No dice. Does anybody know how to do this?
-D
| I've written code a bit like this, where I wanted to put a tree view inside a combo box and I needed to take an action when the check box on the tree was clicked. What I ended up doing was installing an event filter on the combo box to intercept mouse clicks, figure out where the mouse click was happening, and then ta... |
2,389,169 | 3,392,775 | How do I get missing prototype warnings from g++? | I currently have a project that uses g++ to compile it's code. I'm in the process of cleaning up the code, and I'd like to ensure that all functions have prototypes, to ensure things like const char * are correctly handled. Unfortunately, g++ complains when I try to specify -Wmissing-prototypes:
g++ -Wmissing-prototy... | Did you try -Wmissing-declarations? That seems to work for g++ and detect the error case you describe. I'm not sure which version they added it in, but it works for me in 4.3.3.
|
2,389,270 | 2,389,296 | Visual Studio - can be a breakpoint called from code? | I have a unit test project based on UnitTest++. I usually put a breakpoint to the last line of the code so that the I can inspect the console when one of the tests fails:
n = UnitTest::RunAllTests();
if ( n != 0 )
{
// place breakpoint here
return n;
}
return n;
But I have to reinsert it each time ... | Use the __debugbreak() intrinsic(requires the inclusion of <intrin.h>).
Using __debugbreak() is preferable to directly writing __asm { int 3 } since inline assembly is not permitted when compiling code for the x64 architecture.
And for the record, on Linux and Mac, with GCC, I'm using __builtin_trap().
|
2,389,391 | 2,389,430 | Running function from an unmanaged dll inside a C# thread | Here's my problem:
I have an unmanaged dll that I made.I'm calling one of this dll's functions in my C# code, using PInvoke.
Under certain conditions, in the dll function, I want to be able to terminate the thread that is running the function.How would I achieve that?
Sorry if it is a stupid question, but I'm a total n... | Man, that sounds dangerous. Why terminate the thread? You might be in a thread you don't own depending on how you're marshalling the call. Either ways, it seems like your best option is to return something to indicate you want to terminate the thread and have the managed code handle it gracefully. Don't try to kill the... |
2,389,472 | 4,054,371 | string conversion between UTF-8 representation and unicode representation | How to design an algorithm to convert a UTF-8 string to a unicode string?
| The commenters are right. Read http://en.wikipedia.org/wiki/Unicode and rephrase question.
UTF-8 is a ''represenation'' of unicode. You probably want to recode to some other interpretation, maybe Java Strings or Microsoft Visual C++ multibyte chracter strings...
|
2,389,520 | 2,389,594 | Class structure for an inventory control system | As an exercise in good OO methods and design, I want to know what is a good way to model inventory control in a company. The problem description is
a. A company can have different types of items, like documents (both electronic and physical), computers etc which may further have their own sub types.
b. The items can b... | Answering your question would need deep investigation of the problem domain. I don't think there is a universally valid approach.
There are some patterns that are likely to appear, though. One of them (and one of the most difficult to implement, by the way), is the type/instance pattern. Based on my experience, I am as... |
2,389,527 | 2,784,084 | Boost.Program_options fixed number of tokens | Boost.Program_options provides a facility to pass multiple tokens via command line arguments as follows:
std::vector<int> nums;
po::options_description desc("Allowed options");
desc.add_options()
("help", "Produce help message.")
("nums", po::value< std::vector<int> >(&nums)->multitoken(), "Numbers.")
;
p... | The boost library only provides the predefined mechanisms. A quick search didn't find something with a fixed number of values. But you can create this yourself. The po::value< std::vector<int> >(&nums)->multitoken() is just a specialized value_semantic class. As you can see, this class offers the methods min_tokens and... |
2,389,583 | 2,389,682 | Need to traverse matrix-like graph in expanding concentric squares | Ok, I've a data structure that consists of a matrix of linked nodes, lets say 10x10. I would like to be able to choose any of these nodes arbitrarily, and - from there - process a number of the surrounding nodes following the pattern of expanding concentric squares (I used less nodes below for illustration purposes). A... | function scan( x, y ){
queue toDo;
set queued;
toDo.push( x, y );
queued.add( x, y );
while ( !toDo.empty() ) {
(x, y) = toDo.removeHead();
if ( process( x, y ) != stop ) {
for( xp = -1; xp <= 1; ++xp ) {
for( yp = -1; yp <= 1; ++yp ) {
... |
2,389,663 | 2,390,174 | First while loop's first iteration always fails to take input. 2+ loops work fine | The bug starts at cin.getline ( string, 25, '\n' ); or the line below it (strtod). If I use cin, it works, except I cannot quit out. If I type anything that's not a double, an infinite loop runs. Need help. Basically, the first iteration runs, does not ask for input, so the user gets the math questions wrong. The secon... | The problem is this line:
cin >> choice;
This line parses the input buffer for character input that can be converted to an integer. So if you enter:
2<newline>
The string "2" is converted, and <newline> remains in the input buffer; so the subsequent cin.getline() is satisfied immediately.
This is also why JonH's sug... |
2,389,886 | 2,389,988 | How do I strong name a C++ assembly in VS2008? | I have no experience developing C++ on Windows, but I am a C# developer.
I have a wrapper around some native DLLs that is written in C++. (A LGPL project)). I was to use this from a strong named assembly.
How do I set up the strong naming of the C++ assembly? There is no 'Signing' properties tab available as there i... | I found it. For some reason the first time I clicked on the project the property pages came up empty. On retry I found it in the project property page.
Configuration Propertyes|Linker|Advanced|Key File.
And just enter the path to the snk key file.
Thanks for looking.
|
2,390,131 | 2,390,154 | printf question with a const char* variable | I am stuck in a printf problem. I would appreciate if I can get some help here:
In the below code, I can see the font family get displaced correctly in first printf(),
but if I set it to variable, i only get an empty string. How can I put it in a variable and have the right values? I just don't want to type 'font.famil... | Something in the chain of font.family().family().string().utf8().data() is returning a temporary object. In your first printf, the temporary object doesn't go out of scope until the printf returns. In the second printf, the temporary has been destroyed after the pointer assignment was made, and the pointer is now inval... |
2,390,782 | 2,390,838 | OpenGL texture mapping on sides cube using GL_QUADS | I am trying to map a different texture on each side of a cube using a GL_QUADS. My first problem is that I cannot even get a texture to display on the side of a GL_QUADS. I can however get a texture to display using GL_TRIANGLES but I do no understand how to draw things very well using triangles and I want to use QUADS... | Oops didn't realize I forgot to use glTexCoord2f. It works now.
|
2,390,861 | 2,390,880 | Checking ignore() for values | When you use ignore() in C++, is there a way to check those values that were ignored? I basically am reading some # of chars and want to know if I ignored normal characters in the text, or if I got the newline character first. Thanks.
| I don't believe so - you'd have to "roll your own".
In other words, I think you'd have to write some code that read from the stream using get(), and then add some logic for keeping what you need and ignoring the rest (whilst checking to see what you're ignoring).
|
2,390,897 | 2,390,956 | C++ inheritance, base functions still being called when overriden | I have the following two classes, one inherits from the other
Class A{
void print(){cout << "A" << endl;}
}
Class B : A{
void print(){cout << "B" << endl;}
}
Class C : A{
void print(){cout << "C" << endl;}
}
Then in another class I have the following:
vector<A> things;
if (..)
things.push_back(C());
else if (... | As mentioned, you need virtual functions to enable polymorphic behaviour and can't store classes directly by value in the vector.
When you use a std::vector<A>, you are storing by value and thus objects that you add, e.g. via push_back() are copied to an instance of an A, which means you lose the derived part of the ob... |
2,390,911 | 2,391,231 | SSPI Negotiate not found | I'm using Windows XP Pro SP3.
I want to use SSPI functions in my code.
I compiled my code, no error.
I set the security package to be used to Negotiate, which is recommended.
When I start my program, Negotiate cannot be used because it can't be found.
So, I tried "Kerberos" instead, and same error: the security package... | SSPI is a cow to debug without code :)
Try this code, see if it works, if it does, re-try it and replace NTLM with Negotiate. Actually, rather than using the word, "Negotiate" #include "security.h" and use NEGOSSP_NAME.
Also, try this, and see if Negotiate is in the list:
int main(int argc, _TCHAR* argv[])
{
ULON... |
2,390,912 | 2,390,938 | Checking for an empty file in C++ | Is there an easy way to check if a file is empty. Like if you are passing a file to a function and you realize it's empty, then you close it right away? Thanks.
Edit, I tried using the fseek method, but I get an error saying 'cannot convert ifstream to FILE *'.
My function's parameter is
myFunction(ifstream &inFil... | Perhaps something akin to:
bool is_empty(std::ifstream& pFile)
{
return pFile.peek() == std::ifstream::traits_type::eof();
}
Short and sweet.
With concerns to your error, the other answers use C-style file access, where you get a FILE* with specific functions.
Contrarily, you and I are working with C++ streams, a... |
2,391,062 | 2,391,073 | Follow-up. Is return reference to x++ defined? | I recently asked the question Is the behavior of return x++; defined?
The result was about what I expected, but got me thinking about a similar situation.
If I were to write
class Foo
{
...
int x;
int& bar() { return x++; }
};
Where bar now returns an int reference, is this behavior defined? If the answ... | No, you cannot do that, as that would be returning a reference to a temporary.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.