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,097,843 | 4,098,097 | Embedded Mono in C++ Starting C# ServiceBase | Is it possible to use a C++ application that has a mono runtime embedded inside of it to perform a mono_jit_exec on a C# app that is a service (uses ServiceBase to start)?
I can start a simple C# application from a C++ app that has a normal C# application (not a service) but I'm having some trouble starting a service.
... | A service would make sense as a separate process, so you would basically execute:
system ("mono-service2 yourprogram.exe") or use fork/exec etc.
|
4,097,991 | 4,098,052 | Running a computer in kiosk mode for a custom Linux C++ app | I want to create a C++ application that is to run on some Linux platform on a specific laptop computer. I do however not want the users of this laptop to use any other applications/system features than this program - much like the kiosk modes you would find on computers in a typical internet café.
One issue is that th... | This shouldn't be on stackoverflow but anyway:
Run a plain X session with no window manager, into this plain X session start your program in fullscreen. Done.
I run a small XUL application this way:
X :10 &
sleep 10
DISPLAY=:10 xulrunner ~/zkfoxtemp/application.ini
|
4,098,065 | 4,098,217 | Why do you _have_ to initialize a C++ static member variable? | I know that you generally initialize a static member variable from within a .cpp file. But my question is: why do you have to?
Here's an example:
#include <vector>
using namespace std;
class A {
public:
static vector<int> x;
};
main() {
int sz = A::x.size();
}
This gives a compiler error: undefine... | That's not about initialization, it's about definition.
Or more precisely : it's about knowing which compilation unit (.cpp) will hold the object (that have to be uniquely defined SOMEWHERE)
So, what's needed is simply to put the definition somewhere, in a unique place, that is a cpp, to let the compiler know that when... |
4,098,103 | 4,098,236 | Auto-generated C++ file in the Pre-build not included in the compilation | I have a custom parser that generate C++ files and add them into a project. What I would like to do is call this parser before building my project and compile the new generated files in the same build. I use VS2010. I tried to call the parser in the PreBuild, the generated files are correctly added in the project (I ca... | I'm not sure, but do not fully know, if files added to the project during the PreBuild phase are actually included in the compilation. I believe that the files included is calculated before the PreBuild phase is run.
One way to work around this though is to add an empty file into the project and include it in the co... |
4,098,182 | 4,098,256 | Access violation writing location error when using strcat | I am having problems when using the strcat function in C++.
If I do :
MyClass::MyClass(char* myString){
char* AnotherString = myString;
strcat(AnotherString, "bob");
}
Then everything is fine. However, if I do:
MyClass::MyFunction(){
char* AnotherString = "fred";
strcat(AnotherString, "bob");
}
I get an unhandle... | First, the compiler shouldn't allow you to compile this (without warnings):
char* str = "fred";
The correct code is:
const char* str = "fred";
String literals are constants, therefore you can't modify their contents.
|
4,098,261 | 4,098,818 | Is it possible to store pointer with two higher-order zero bytes as a WORD when it's not in a cpu register? | On a system where size of a pointer is 4 bytes when the intention is to just address parts of memory that are addressable by two bytes(lower parts), is it possible to store the pointer as a two byte WORD when it's not in some cpu register? I don't see any way cause assuming we've got any WORD like one named "twoBytes" ... | What you are describing sounds more like a compiler feature (good old fashioned "near" pointers) than something you can do from inside the language. Take it up with whoever made the compiler you're using. I can vouch for the theoretical possibility of being able to implement this behavior in GCC, although I suspect i... |
4,098,455 | 4,098,798 | Is it thread safe to call async_send and async_receive at the same time? | I understood that calling boost::asio::ip::tcp::socket::async_receive (or boost::asio::ip::tcp::socket::async_send) two times may result in a bad behavior..
Is it OK if i call boost::asio::ip::tcp::socket::async_recive and boost::asio::ip::tcp::socket::async_send at the same time?
I am going to have 2 or more threads r... | This has to be OK. How else would you perform full duplex async communications on a single service? You need a receive outstanding at all times for incoming data.
The Boost docs indicate only that each of async_read and async_write must be called serially. For example, for async_read:
The program must ensure that t... |
4,098,509 | 4,098,551 | Collecting, storing, and retrieving large amounts of numeric data | I am about to start collecting large amounts of numeric data in real-time (for those interested, the bid/ask/last or 'tape' for various stocks and futures). The data will later be retrieved for analysis and simulation. That's not hard at all, but I would like to do it efficiently and that brings up a lot of questions... | Fame is an often-used commercial solution for time-series storage.
If you are serious about this, building your own will be a big job. HDF might be useful, they claim that it is suitable for tick data handling, and have C++ access. There is Python support here.
Useful real-life experience from somebody with the sam... |
4,099,202 | 4,099,375 | boost asio and the proliferation of shared_ptrs | I've recently started using boost. So far most things have been pretty straight forward. But one thing that is driving me nuts is the proliferation of shared_ptr throughout boost. Even in trivial examples, shared_ptr is used.
So my question is, if I am using boost for accepting tcp connections and then handling them. A... | Read the documentation for the io_service destructor
The destruction sequence described
above permits programs to simplify
their resource management by using
shared_ptr<>. Where an object's
lifetime is tied to the lifetime of a
connection (or some other sequence of
asynchronous operations), a shared_ptr
... |
4,099,204 | 4,099,348 | Call the unspecialized version of a function when specializing it in C++? | Say I have a templated class:
template <typename T>
class foo {
void do_someting(T obj) {
// do something generic...
}
};
and I want to specialize do_something, but within it I want to call the "normal" do_something function:
template<>
void foo<MyObj>::do_something(MyObj obj) {
// do something specific...
... | No. Your specialization is the only definition that will exist for the MyObj type argument. But, consider modifying the foo template in this manner, which will be transparent to the current users of the template:
template<typename T>
class foo {
void prelude(T &obj){ // choose a better name
/* do nothing */
}
... |
4,099,218 | 4,099,483 | Parsing VS2010 MSBuild vcxproj file | I'm currently working on a console application that will pass a vcxproj file and compile it using GCC. Unfortunately, I've come up against a whole load of problems pretty much instantly.
I notice a bunch of directory shortcuts such as:
VCTargetsPath
VCInstallDir
SolutionDir
ProjectDir
UserRootDir
and so on.
Where d... | The MSBuild executable (and dependent DLLs) processes those properties the same way it processes any other property in the build file. In this case, they're simply predefined properties that it looks for explicitly.
If you really want to dig into it, open up the Microsoft.Build.dll in Reflector and look for the Micros... |
4,099,239 | 4,099,271 | const question when used in API | I have a char * that is actually 10 digit string. I basically take that in my function and spit out a code. Now i have made a static lib that i will share with someone else...the question is ( i am using c++)
for the definition of that api that i will provide in my header
do i just put const char * const or not. I am ... | Making something const does not mean that you won't get a bad pointer. There's nothing you can do to guard yourself against that. You can check for NULL, but not a freed pointer or a corrupted one.
What const says is that your function promises not to change the data that is pointed to. That's useful for the caller ... |
4,099,389 | 4,099,436 | Why does std::copy (from istream to ostream) raises an ios::failure exception? | The following code should copy data from an wifstream to wcout.
After the content is copied, the program throws a ios::failure exception.
#include <string>
#include <iostream>
#include <sstream>
#include <fstream>
#include <locale>
#include <iterator>
#include <algorithm>
int main(void)
{
std::locale::global(std:... | To avoid skipping white space use the std::istreambuf_iterator
std::copy(std::istreambuf_iterator<wchar_t, wchar_t>(is),
std::istreambuf_iterator<wchar_t, wchar_t>(),
std::ostream_iterator<wchar_t, wchar_t>(std::wcout));
The exception:
The local may be using codecvt facet that is failing.
Try comme... |
4,099,603 | 4,099,677 | Trying to avoid segmentation fault, but my output looks weird (C++) | A homework project I'm working on uses static and dynamic arrays. However, I'm not implementing the dynamic arrays yet and this is a weird discrepancy trying to get the length of my static arrays.
I used a series of cout statements to try and find out what was giving me a segmentation fault, since the process seemed st... | Your function is actually doing something you don't realize - it decays the array you pass into a pointer to the first element.
Basically your function signature: String::String( const char Input[] ) would be equivalent to the signature String::String(const char *input).
So when you do sizeof, you're actually getting t... |
4,099,657 | 4,104,336 | Calling CUDA code from regular C++ code - sorting out the extern "C" | I am trying to call a CUDA (host) function from a C++ file, compiled separately:
sample.cpp C++ file:
extern "C" void cuda_function(int a, int b);
int main(){
//statements
cuda_function(23, 34);
//statements
}
cuda.cu file:
#include <cuda.h>
__global__ void kernel(int a, int b)
{
//statements
}
void cuda_funct... | You have declared cuda_function() as extern "C", but then defined it using C++. Remove the extern "C" from your delcaration and it will work.
Alternatively, but pointlessly, you could add the same declaration to the cuda.cu file.
To elaborate a little, nvcc is a wrapper which splits a file into host code and device cod... |
4,099,804 | 4,100,222 | How to find programmatically location of a dynamic library file? | I want to find the path in the system (if any) of a specific library
right now I have a built ins path:
dllNameFrodo = "/usr/local/frodo/lib/libfrodo.dylib";
but of course is ugly and not portable.
Any ideas ?
| Instead of trying to load a hardcoded path, either package the library locally with your application so you know where it's installed, or better yet, just let the runtime loader find and load it automatically. This way the user can fiddle with LD_LIBRARY_PATH and LD_PRELOAD to pick which version to load.
|
4,099,863 | 4,099,915 | C++: Recommendations for Member Function Access at the Same Architecture Layer | I have 4 classes of the following hierachy:
MyTop
|
-------------------
| | |
BlockA BlockB BlockC
BlockA, BlockB, and BlockC are the composed objects of MyTop. BlockA provides a function LookUpTable(), and BlockB and... |
I thought about implementing the
look-up table as a class itself, but
the content of the loop-up table is
slightly coupled with the
initialization of BlockA, and it may
not be trivial to decouple the table
from BlockA (it's still doable, but
not preferred).
Can't you simply make BlocA intialize that loo... |
4,100,146 | 4,101,013 | Char type on 32 bit vs 64 bit | Here is the following issue:
If I am developing on a 32 bit machine and want my code to be ported to a 64 bit machine here is the senario.
My function internally use a lot of std strings. Now if I want to provide APIs can I ask them to send char * which I can then use internally? Or ask them to send me a __int64 which ... | You seem somewhat confused. If the code you are writing is used only within the target machine, recompile will take care of most of the problems. Just don't rely on specific memory layout and you are fine. Using strings (as opposed to wstrings) probably means that the character encoding is UTF-8 (if not, reconsider) an... |
4,100,196 | 4,102,576 | Grid, flexgrid, or gridbag layout for MFC | MFC seems to have a severe lack of layout managers/sizers. Hard to believe any self-respecting UI library would lack sizers but there you go. I've found something that will take care of the usual box layout just fine, but what I haven't found is a sizer that will help when you need things to be aligned both verticall... | I haven't heard of a proper fully-featured sizer library for MFC either. And I don't believe there is anything much better than the options mentioned in that linked question.
In my opinion, I doubt any such thing will ever be made at this point. Other well-established GUI frameworks already have proper sizer features i... |
4,100,263 | 4,100,583 | C++ multi threading data structure for communication between two threads | I have a thread that calls various APIs of a COM interface. Now I want to invoke these functions from another thread. Can you please advise how I can achieve this?
How can I implement the communication between these two threads? If I define a Message queue sort of data structure which is common for these two threads th... | You don't define one common data structure. There is a different data structure for each different function signature. Only common thing between those structures is identifier of the function. In your thread you'll have giant switch (or std::map) that would translate function identifier to function itself. After that y... |
4,100,284 | 4,100,348 | Does iterator support + operator? | I saw the following code used to delete one selected element from std::vector:
vector<hgCoord>::iterator it;
int iIndex = 0;
const int iSelected = 5;
for( it = vecPoints.begin(); it != vecPoints.end(); ++it, ++iIndex )
{
if( iIndex == iSelected )
{
vecPoints.erase( it );
break;
}
}
I ar... | To make this code generic, so it works no matter whether the iterator supports operator +, and uses the most efficient available implementation:
template <typename C>
void erase_at(C& container, typename C::size_type index) {
typename C::iterator i = container.begin();
std::advance(i, index);
container.eras... |
4,100,657 | 4,100,687 | Problem with my clamp macro | I have a problem with my clamp macro, when when my value is over 10 and my high is over 17 it stops working. Any idea?
#define CLAMP(value, low, high) (((value)<(low))?(low):(((value)>(high))?(high):(value)))
| I would suggest using a safer way than a macro:
template <typename T> T CLAMP(const T& value, const T& low, const T& high)
{
return value < low ? low : (value > high ? high : value);
}
|
4,100,695 | 4,100,783 | Create strings depending on template arguments | I have many classes/methods like this:
template<typename CharT, typename TraitsT = std::char_traits<CharT> >
struct Foo
{
std::basic_string<CharT, TraitsT> getFoo(void) const
{
return "Foo"; // + this->member_var1 + this->member_var2...
}
};
But depending on CharT, I have to use "", L"", u"" or "U" (for ... | Do you really need the different literals, or can you use the iterator constructor?
const char *f = "Foo";
return std::basic_string<CharT, TraitsT>(f, f + 3);
Maybe with something a bit more robust than "3" in there, if you're worried about ease of changing the literal in future.
In response to the point that this isn... |
4,100,715 | 4,101,589 | Drawing a cube in open GL ES1 for the iphone | Hello friendly computer people,
I've been studying openGL with the book iPhone 3D programming from O'Reilly. Below I've posted an example from the text which shows how to draw a cone. I'm still trying to wrap my head around it which is a bit difficult since I'm not super familiar with C++.
Anyway, what I would like to ... | If all you want is an OpenGL ES 1.1 cube, I created such a sample application (that has texture and lets you rotate it using your finger) that you can grab the code for here. I generated this sample for the OpenGL ES session of my course on iTunes U (I've since fixed the broken texture rendering you see in that class ... |
4,100,880 | 4,101,086 | Reading and appending from/to a file with std::fstream | I'm wondering why the following piece of code doesn't work, looks pretty straight-forward, am I making a mistake?
The result of this is: file created but empty, if I manually add lines those lines are showed with this code, but nothing else happens.
#include <fstream>
#include <iostream>
#include <string>
using namespa... | Couple of things:
When you are ready to write, you need to seekp() rather than seekg(), i.e.
mfile.seekp(ios_base::end);
Now, the problem here is that the getline() calls will set the stream flags (specifically eof), and as a result the stream is not ready for further operations, you need to clear the flags first!
try... |
4,100,884 | 4,101,857 | How to get web camera fps rate in OpenCV? | So I need to get web camera fps rate in OpenCV. Which function can do such thing for?
| int cvGetCaptureProperty( CvCapture* capture, int property_id);
with property_id = CV_CAP_PROP_FPS
|
4,100,893 | 4,100,978 | Undefined reference to template members | I'm new to C++, and preparing a homework by using NetBeans IDE on Ubuntu 10.04. I use g++ as a C++ compiler.
The error message:
build/Debug/GNU-Linux-x86/Maze.o: In function `Maze':
Maze/Maze.cpp:14: undefined reference to `Stack<Coordinate>::Stack()'
Maze/Maze.cpp:14: undefined reference to `Stack<Coordinate>::Stack()... | Stack is a template. The complete definition has to go in its header file. That is, do not separate it into a .h and a .cpp file.
|
4,100,995 | 4,101,486 | C++ Threaded Stopwatch | I am trying to create a stopwatch in C++, something similar to Java's TimerTask. I like their library since it already has threading built in. I have seen Boost Chrono, however, it's still in development and would prefer not to use it.
My current implementation has been without luck (I am going by memory right now so t... | You nearly have it, because you're creating a new thread to handle io_service::run(), your main thread will not block. Two things you need to do,
ensure you call Start() before you Initialize() (using the same io_service instance), this way there is something for the io_service to do, else it will quit!
On your Handl... |
4,101,130 | 4,101,158 | How to write Python bindings for command line applications | I'm interested in writing a python binding or wrapper for an existing command line utility that I use on Linux, so that I can access its features in my python programs. Is there a standard approach to doing this that someone could point me to?
At the moment, I have wrapped the command line executable in a subprocess.P... | If you must use a command line interface, then subprocess.Popen is your best bet. Remember that you can use shell=True to let it pick the path variables, you can use os.path.join to use OS-dependent path separators etc.
If, however, your command line utility has shared libraries, look at ctypes, which allows you to con... |
4,101,332 | 4,101,377 | A Question About Inheritance In My Game | I have a Player class that derives from Humanoid and Humanoid derives from Sprite like so
Sprite -> Humanoid -> Player
So far so good. Sprite has the virtual method
virtual sf::Sprite getSprite() { return sprite_; }
where sprite is an image object that can be drawn onto the screen.
Humanoid declares virtual sf::Spri... | If the Sprite class has a sprite_ member and none of the derived classes (Humanoid/Player) have added a member with the same name then there is only one sprite_ object for each instance and the function should work as expected. I don't understand why you're overriding getSprite if you give it the exact same behaviour t... |
4,101,584 | 4,101,613 | c++ create class using headers and cpp files | im creating class so i can understand them better. when im creating a class what should header files be used for and cpp?
| Header files is for the class definition and the cpp file for the implementation. Something like this:
Test.h
class Test
{
public:
void PrintHelloWorld(void);
};
Test.cpp
void Test::PrintHelloWorld(void)
{
cout << "Hej på dig världen!";
}
|
4,101,625 | 4,101,662 | C++ to C#: cin to Console.Read | Is there a way to read multiple inputs on the same line in C# like I would in C++?
I have included an example:
#include <iostream>
#include <string>
using namespace std;
int main ()
{
cout << "Format: name age"<< endl;
int age;
string name;
cin >> name >> age;
return 0;
}
| String.Split is the obvious solution here:
string input = Console.ReadLine();
string [] split = input.Split(` `);
Then use the resultant array.
You lose your "nice" variable names and have to convert from string to int - but you'd have to do that anyway.
You can specify a set of split characters:
string [] split = wor... |
4,101,666 | 4,101,976 | C++ iterate through a 2D vector to find 3 in a row | Hey all, working on a C++ little game, "Connect 3." This is just like Connect 4, except we only need a match of 3 to win the game. I am storing my board in a 2D vector, which holds ints.
vector< vector<int> > vector2d;
And I have an "X" stored as a 1, and an "O" stored as a -1, with 0 being an empty space. It seems... | So lets say you are using an 3x3 board. There are a finite number of winning lines that can be formed.
1 0 0 1 1 1 1 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 1 0
1 0 0 0 0 0 0 1 0 0 1 0 0 0 1 1 1 1 0 0 0 0 1 0
1 0 0 0 0 0 0 0 1 1 0 0 0 0 1 0 0 0 1 1 1 0 1 0
Now if you give each board... |
4,101,700 | 4,101,904 | async_connect blocks io_service::run_one() in boost::asio | I'm trying to run following code:
some_sock.async_connect(...); // handle_connect() sets the 'condition' flag
boost::asio::deadline_timer t(ios, boost::posix_time::seconds(2));
while (t.expires_from_now() >= boost::posix_time::seconds(0))
{
ios.run_one();
if (condition) return;
}
Desirable behavior is return from... | use io_service::run and deadline_timer::async_wait as described in the async tcp client example.
|
4,101,856 | 4,102,991 | Global variables (again) | I keep hearing that global variables should never be used, but I have a tendency to dismiss "never" rules as hot-headed. Are there really no exceptions?
For instance, I am currently writing a small game in c++ with SDL. It seems to me to make a lot of sense to have a global variable with a pointer to the screen buffer,... | Of course there are exceptions. I personally can't think of a single situation where a goto is the right solution (or where a singleton is the right solution), but global variables occasionally have their uses. But... you haven't found a valid excuse.
Most objects in your game do not, repeat, not need to access the sc... |
4,101,864 | 4,101,897 | Windows unicode commandline argv | So getting into the new millenia I rewrote my c++ code with:
int main(int argc, wchar_t **argv)
If built with either Unicode or MBCS options then when the app is run with a commandline arg, either directly or by dbl-click the filenames passed to argv[] are unreadable = in some mixture of chinese fonts.
Thanks for the ... | You need to name your entry point wmain: http://msdn.microsoft.com/en-us/library/fzc2cy7w(VS.80).aspx
|
4,102,150 | 4,102,309 | The difference between signed bytes and parity bytes | I'm reading some bytes out of a byte stream and they look like this:
OUTPUT:
48 -84 -79 -84 -73 -79 46 48 -84
SHOULD BE:
48 44 49 44 55 49 46 48 44
I'd like to turn these into ascii characters but those negitive symbols are confusing me. This makes me think I don't understand signed bytes. What on earth am I ... | Looks like the highest bit is used as a parity bit, while your code assumes it is a sign bit.
48 = 011 0000 : 2 bits set -> add 0
-> 0011 0000 = 48
44 = 010 1100 : 3 bits set -> add 1
-> 1010 1100 = -84
49 = 011 0001 : 3 bits set -> add 1 -> 1011 0001 = -79
and so on...
Solution: mask away the highest bit by using... |
4,102,202 | 4,102,225 | The fastest way to save large data to a file | I do some numerical calculation in Java, C# and C++. Some of them save a lot of data (to the text file). What is the fastest way to do it?
C++.
ofstream file;
file.open(plik);
for(int i=0;i<251;i++){
for(int j=0;j<81;j++)
file<<(i-100)*0.01<<" "<<(j-40)*0.01<<" "<<U[i][j]<<endl;
file<<endl;
}
Which I ... | Profile it. Run the code, time it, see how long it takes. If the amount of time it takes is acceptable, use it. If not, figure out what piece is taking a long amount of time to run, and optimize it.
Make it right.
Make it fast.
That order. (Some people add "make it run/build" before those two...)
That said, I've actu... |
4,102,253 | 4,102,261 | C++, Modifying vector elements using its pointer | I wish to avoid switch statement by defining a pointer to a vector.
I need help to use insert and erase methods.
bool selectFirst = true;
std::vector<int> v1, v2;
std::vector<int> *v = selectFirst ? &v1 : &v2;
v->push_back(0);
But how to insert or erase values from v ???
Thank you
| Well, the same way you used push_back, you can use erase... Look at the documentation for those operations in the STL. For example, deleting the first element:
v->erase( v->begin() );
|
4,102,320 | 4,102,533 | How to encrypt strings at compile time? | I want to hide some strings in my .exe so people can't simply just open the .exe and look at all the strings there. I don't care about the strength of the encrypting method, so I will probably use XOR etc.
How can I do this at compile time? That way my strings won't be stored in the .exe but the encrypted versions wou... | you can encrypt it using macros or write your own preprocessor
#define CRYPT8(str) { CRYPT8_(str "\0\0\0\0\0\0\0\0") }
#define CRYPT8_(str) (str)[0] + 1, (str)[1] + 2, (str)[2] + 3, (str)[3] + 4, (str)[4] + 5, (str)[5] + 6, (str)[6] + 7, (str)[7] + 8, '\0'
// calling it
const char str[] = CRYPT8("ntdll");
|
4,102,328 | 4,102,433 | How can I implement this with Polymorphism? | My game gui api supports 2 backends. They both work similarly and use event queues. The problem is that I do not want my API to handle the whole game's events, only peek at an event and do something, then let the game do whatever with it. That's why I cannot just give it the event queue. My issue is that, I will have a... | Well, this depends on a number of different factors, but I suspect you will want double-dispatch (for this particular kind of scenario), unless your event types have similar characteristics and handling behavior. In either case, you should have a pure virtual base class representing an arbitrary event, and then you sho... |
4,102,411 | 4,102,552 | Abstract Factory, Dependency Injection and good Design | I am trying to get the knack of good system design. As there is no hard and fast rules for good system design, I request you to give me some valuable suggestions. I prepared an imaginary system and prepared a design for that. Please let me know if you think if this design is good or bad. Is there a better way? I used A... | I'd remove the dependency between factories (actually apply dependency injection) and VWGolf and I'd make sure to be using RAII instead of raw pointers. You're main should look more like so:
void main() // still not applying RAII
{
GTFactory factory;
VWGolf golfGT(factory.CreateEngine(), factory.CreateElectrical()... |
4,102,598 | 4,102,735 | Counted semaphore in Linux? | Are there any counted semaphores in Linux?
What I'm wanting to do is keep track of how many readers a resource has.
| POSIX semaphores
You might also consider the Boost C++ Libraries. Boost has a bunch of different threading and synchronization related components, including an abstraction for semaphores, and also a good implementation of the ReaderWriterLock. Check out this SO post, regarding Boost ReaderWriterLock.
|
4,102,635 | 4,102,666 | C++ function pointer | Is there a way in C++ to make an "untyed" function pointer ?
For example:
// pointer to global function
void foo( void (*fptr)() );
// pointer to member
void foo( void (Bar::*fptr)() );
Is there a way I can remove the class on which the member is ? So that I could do something like this:
void foo( void ("any type"::*... | You can use a template.
template<typename T> void foo( void(T::*)(), T&) { ... }
However, people prefer to go for the function object approach. You can do this dynamically or statically.
void foo(std::function<void()> func) {
// std::bind is used to make this out of a member function
}
template<typename T> void fo... |
4,102,811 | 4,103,005 | Where to get simple Boost Thread Management example? | So I have a simple cpp file. Only one with one main function and 3 int a-la public variables. like:
int a;
int b;
int c;
void main()
{
startThredA();
startThredB();
while(1)
{
c = a + b;
printf(c);
}
}
I whant to create 2 threds A and B one of which should... | Here is a small and simple example. It's tried and seems to work fine.
#include <iostream>
#include <boost/thread.hpp>
namespace this_thread = boost::this_thread;
int a = 0;
int b = 0;
int c = 0;
class BaseThread
{
public:
BaseThread()
{ }
virtual ~BaseThread()
{ }
void operator()()
... |
4,102,890 | 4,103,794 | The "concept" of an oo game | In most or all object oriented games, each class relies on not just its own but parent classes. How is this class connection implemented in C++? Do you just add a pointer for the parent class you need or is there a better way?
For example a football game, when the person class clicks it ask the scene class if he is kic... | I don't think passing along the parent in a constructor is a good idea. Instead, you should be using a class that maintains a list of all game elements and facilities interactions between them; for instance, the Game class illustrated below would check for collisions between any two players and if it's detected tell e... |
4,102,913 | 4,102,962 | Is there a way for a derived implementation of a base function to access a class where base is a friend? | Here is my issue. I have a container which takes in a pointer to the base class. When the container calls a certain method declared virtual, the derived classes can modify a pointer to the container, but only the base is a friend and since the container is compiled as a dll, it is not convenient to add friend Derived; ... | Friendship is not inherited.
You have at least two options:
Change the "container" to expose an interface that the derived classes can use
Have the base class expose an interface to any classes derived from it
Without more details it's hard to tell, but it sounds like this architecture has rather poor encapsulation.
|
4,102,949 | 4,102,978 | accessing parent namespace in c++ | I am using two 3rd party frameworks. I want to access a new class from both frameworks.
The first framework uses a nested namespace like:
namespace space1 {
namespace space2 {
class 3rdparty{
}
}
}
the second framework doesn't use any namespaces.
If I try to call my own class from the first fr... | To access a parent scope, use a double colon (::) as in:
class Blah;
namespace alpha
{
class Blah;
}
namespace bravo
{
class Blah;
// can access outer class as ::Blah
// and one from alpha as ::alpha::Blah
}
Note, though, that in your example the following code should not compile:
3rdparty::3rdp... |
4,103,009 | 4,103,019 | C++ - Too Many Include Files? & Struct Redefinition? | I am currently writing a token recognizer for XML. I am going along the basis of FSA's to do so. So I have a Header file that has the following code...
#define MAX_LENGTH 512
#define MAX_NAME 25
struct token
{
char name[MAX_NAME + 1];
int type;
unsigned char str[MAX_LENGTH + 1];
};
#define TOKEN_TYPES 8... | I assume you're somehow including your header file twice. Do you have a guard against that? Every header file should have this:
#ifndef TOKEN_H
#define TOKEN_H
[your header file code]
#endif
If that's not it, make sure you're not defining token twice somewhere else.
|
4,103,024 | 4,103,091 | C++: How to deal with NULL values (e.g. from a database)? | In C++, how to deal with NULL values in a context where we might expect a string or an integer?
Typically, the context would be when retrieving data from a database, e.g. with a LEFT JOIN where some non-existing values in some column would be represented by a NuLL value instead of the expected string or integer.
Strong... | It may sound like a general concept, but there is no general answer for C++. The language itself does not have a truly general "NULL" value that can by used with all types to distinguish from having been set to an actual value.
So the answer in any situation entirely depends on the library or whatever that you're worki... |
4,103,062 | 4,107,447 | Curl CONNECTTIMEOUT question | If you curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 15); and 15 seconds passes and no connection is made, what will happen?
| According to this mailing list thread, the documentation for curl_easy_setopt and the documentation for curl_easy_perform, the call to curl_easy_perform will fail with error code CURLE_OPERATION_TIMEOUTED as defined in <curl/curl.h>.
|
4,103,086 | 4,103,123 | #defining constants in C++ | In various C code, I see constants defined like this:
#define T 100
Whereas in C++ examples, it is almost always:
const int T = 100;
It is my understanding that in the first case, the preprocessor will replace every instance of T with 100. In the second example, T is actually stored in memory.
Is it considered bad pr... |
Is it considered bad programming practice to #define constants in C++?
Yes, because all macros (which are what #defines define) are in a single namespace and they take effect everywhere. Variables, including const-qualified variables, can be encapsulated in classes and namespaces.
Macros are used in C because in C, ... |
4,103,109 | 4,103,167 | using std::sort with boost::bind | I'm trying to use boost::bind with the std::sort function. I want to bind sort into a function taking no parameters and specify an int array to sort.
I'm running into issues with what to specify as the template parameter when binding sort, if I was using a standard container I would just use std::container<int>::iterat... | When you want "iterators" into an array, you use pointers to elements in the array. Such pointers can be used as random access iterators:
boost::function<void()> sortHolder =
boost::bind(&std::sort<int*>, nums, nums + NUM_VALUES);
|
4,103,169 | 4,103,178 | How do I include the string header? | I'm trying to learn about strings, but different sources tell my to include different headers.
Some say to use <string.h>, but others mention "apstring.h". I was able to do some basic stuff with apstring, but I've been told the other one is more powerful. When I include <string.h> and try to declare some string varia... | You want to include <string> and use std::string:
#include <string>
#include <iostream>
int main()
{
std::string s = "a string";
std::cout << s << std::endl;
}
But what you really need to do is get an introductory level book. You aren't going to learn properly any other way, certainly not scrapping for inform... |
4,103,315 | 4,662,515 | How to get a IHTMLElement pointer to the <object> tag hosting an activex control | I have an ActiveX control generated by the FireBreath framework (http://firebreath.org). I need to get a reference to the <object> tag in the page that hosts the plugin from C++.
If I were using NPAPI, I would use the NPNVPluginElementNPObject constant with NPN_GetValue.
so to make sure I am being clear, say I have th... | Thanks to FireBreath contributor jtojanen from Finland, we finally have a solution.
The first thing is that the COM object must be registered as "Apartment", not "Single" (in the registry). Otherwise, this will not work; seems to be a bug in COM.
Then anywhere after SetClientSite is called, you can do the following:
CC... |
4,103,340 | 4,103,580 | How do you build an application in c++ modularly | This is a question more about how to build a c++ application than it is about c++, per se
I'm building an application that was envisioned as a Graphical application, but the specifics of the implementation require a great deal of abstract functionality to facilitate the interface, such as reading lists of objects from... | I guess this would be the general tactic for any OO project.
First determine the main components and make sure you have a very thorough understanding of what everything is responsible for.
Write out the interface for each component, and check (logically) to see that it fits your problem.
Implement each module.
As far a... |
4,103,477 | 4,103,661 | Probability density function from a paper, implemented using C++, not working as intended | So i'm implementing a heuristic algorithm, and i've come across this function.
I have an array of 1 to n (0 to n-1 on C, w/e). I want to choose a number of elements i'll copy to another array. Given a parameter y, (0 < y <= 1), i want to have a distribution of numbers whose average is (y * n). That means that whenever ... | dmckee is actually correct, but I thought that I would elaborate more and try to explain away some of the confusion here. I could definitely fail. f_s(l), the function you have in your pretty formula above, is the probability distribution function. It tells you, for a given input l between 0 and n, the probability that... |
4,103,603 | 4,103,610 | What is the worst problem that would occur if pointers were disabled in C++? | As the topic says - What is the biggest problem that would occur if we dropped usage of pointers and resorted to only references in C++? Let's say we have a new that returns a reference and a delete which takes one.
| It would make the language effectively unusable because references in C++ are not assignable.
Once you initialize a reference to refer to a given object, it can't ever refer to any other object.
|
4,103,688 | 4,103,706 | Why is this a pointer |
Possible Duplicate:
Why 'this' is a pointer and not a reference?
Why is this a pointer, rather rhan reference? Can it ever be NULL?
|
Why is "this" not a reference?
See Bjarne's answer here
Because "this" was introduced into C++ (really into C with Classes) before references were added. Also, I chose "this" to follow Simula usage, rather than the (later) Smalltalk use of "self".
|
4,103,707 | 4,103,842 | Need a better wait solution | Recently I have been writing a program in C++ that pings three different websites and then depending on pass or fail it will wait 5 minutes or 30 seconds before it tries again.
Currently I have been using the ctime library and the following function to process my waiting. However, according to my CPU meter this is an u... | To stay portable you could use Boost::Thread for sleeping:
#include <boost/thread/thread.hpp>
int main()
{
//waits 2 seconds
boost::this_thread::sleep( boost::posix_time::seconds(1) );
boost::this_thread::sleep( boost::posix_time::milliseconds(1000) );
return 0;
}
|
4,104,010 | 4,104,395 | cuda float point precision | Can someone comment on this,
I want to do a vector dot product. My float vector are [2080:2131] and [2112:2163], each one of them contains 52 elements.
a[52] = {2080 2081 2082 ... ... 2129 2130 2131};
b[52] = {2112 2113 2114 ... ... 2161 2162 2163};
for (int i = 0; i < 52; i++)
{
sum += a[i]*b[i];
}
The result s... | Since the vectors are float you are experiencing rounding errors. Matlab will store everything with much higher precision (double) and hence won't see the rounding errors so early.
You may want to check out What Every Computer Scientist Should Know About Floating Point by David Goldberg - invaluable reading.
Simple dem... |
4,104,325 | 4,104,339 | Dividing a set (C++) | I've got a std::set<int> which has n items in it. And I want to get rid of n-k bigger elements and keep the first (least) k elements. How should I do so? Is there a pre-defined function for this?
| A std::set is ordered.
std::set<int>::const_iterator i = myset.begin();
std::advance(i, k);
myset.erase(i, myset.end());
|
4,104,544 | 4,104,571 | How to access static members of a class? | I am starting to learn C++ and Qt, but sometimes the simplest code that I paste from a book results in errors.
I'm using g++4.4.2 on Ubuntu 10.04 with QtCreator IDE. Is there a difference between the g++ compiler syntax and other compilers? For example when I try to access static members something always goes wrong.
... | You've declared the static members fine, but not defined them anywhere.
Basically what you've said "there exists some static member", but never set aside some memory for it, you need:
int A::x = 100;
Somewhere outside the class and not inside main.
|
4,104,759 | 4,104,976 | Is it necessary to have static constructors when we follow the "RAII " way of doing things in C++? | If I were to follow the RAII rule and would be developing a class in C++, would it be necessary to have static constructors? Will static constructors help me in any way or would be a wrong step to do?
| I take it you are talking about a static factory function that creates an instance of your class (As others pointed out). In which case, you don't need to use the RAII pattern.
Remember you need your class to be stack allocated, so that the
constructor is called (automatically) and initializes various data.
also, the ... |
4,104,774 | 4,104,808 | The value of ESP was not saved properly |
From the above image you can see that an error occurs when the function setAttribute returns from its call.
Does anyone know how to resolve this error shown in the picture? I know that it is an error between calling conventions, but how do I find out what the calling convention for setAttribute is?
| This error indicates that your stack is corrupted. There are many ways to get there. As mentioned in the error message a different calling convention is possible but this is not often the case.
It is much more likely that your stack has been overwritten by writing to memory pointed to by an invalid pointer.
|
4,104,820 | 4,104,956 | isFollowingCamelCaseConventionInCPlusPlus more_import_than_readability? | I'm moving back from Python to C++ for my next project.
I know why I shouldn't and I know why I should. Never mind that debate.
C++ conventionForVariablesIsCamelCaseAndI'mHavingTroubleAcceptingIt as, at_least_for_my_eyes_it's_less_readable_than_the_lower_case_underscored_convention.
Did any of you encounter an article ... | There is no agreed upon convention for C++ naming among C++ programmers, however lower case with underscores is used in both the C++ standard library and in boost.
As for the coding standards document you linked...
A link to a random company's coding standards that use "Common practice in the C++ development communit... |
4,104,841 | 4,105,018 | C++ sin wave formula for pogo stick jumping | I need to create a pogo stick that jumps across the screen in arcs. I was thinking the best way to do this would be to move it on a sin wave. If the top of the wave is 1, the ground is 0 and the bottom of the wave is -1, then every time it hits 0 I would reset the values to start the sin wave again. So instead of follo... | Not sure about your math, your physics needs some brushing up! The pogo stick is an example of projectile motion and its trajectory forms a parabola, which is described by a quadratic equation.
However should you persist with the incorrect sinusoidal model: The "top half" (or positive) part of a sine wave runs from 0 ... |
4,104,915 | 4,132,053 | Serial port C++ problem | I have a problem connecting to any serial port (want to exchange with an Arduino) using c++ on visual studio.
I'm using the SerialClass given in the Arduino playground, but can't open an handle to my port. It throws ERROR_FILE_NOT_FOUND on every try..
I've been testing many other ways of notating the port:
"COM1"
"COM1... | Found the Answer!
I casted the string using (LPCTSTR), but this wouldn't return a valid string. Had to use
const WCHAR FileFullPath[] = {L"COM4"} ;
for conversion.
|
4,104,941 | 4,105,024 | How do you define a mutable pointer to a const object? | I have a class that contains a pointer to a constant VARIANT value outside the class, but sometimes I want to change this pointer to refer to a VARIANT member object of the class itself.
Most instances of this class will be const, so I have to declare the pointer as mutable.
In Visual C++ this code seems to do what I w... | Comeau online seems to agree with VC++ here.
And it also makes sense! A class member can only be mutable once and there is no such thing as a non-const pointer to a mutable const object. "Mutable const object" doesn't make sense.
You should put the mutable in front of your declaration, as it is in the same area as, for... |
4,105,002 | 4,121,942 | Pass tuple's content as variadic function arguments | I play with C++0x for some time and now I want to use variadic templates and tuple to implement class "Task". I'm going to pass Task objects into newly created threads (using pthread). Task class will contain function pointer to function which should be called inside thread and arguments for this function, simplified c... | It should be equivalent, but the only way to be sure is to test with the compiler you are using.
Note that you could use std::function with std::bind instead, e.g. something like:
template<typename ...T_arguments> class Task : public TaskCaller
{
std::function<bool (T_arguments&...)> functor;
public:
Task (bool... |
4,105,036 | 4,105,083 | An explanation about Sequence points | Lately, I have seen a lot of questions being asked about output for some crazy yet syntactically allowed code statements like like i = ++i + 1 and i=(i,i++,i)+1;.
Frankly realistically speaking hardly anyone writes any such code in actual programing.To be frank I have never encountered any such code in my professional ... | The simplest answer I can think of is:
C++ is defined in terms of an abstract machine. The output of a program executed on the abstract machine is defined ONLY in terms of the order that "side effects" are performed. And Side effects are defined as calls into IO library functions, and changes to variables marked volati... |
4,105,060 | 4,105,087 | When to catch exceptions? | Would there be any difference If i do the following without using exceptions?
void func()
{
try
{
if (n > 5)
{
throw "n is greater than 5";
}
}
catch (const char *e)
{
MessageBox(0, e, 0, 0);
return;
}
}
OR
void func()
{
if (n > 5)
{
... | I would probably say that you best advised not to use exceptions for flow control. Exceptions, as the name suggests, are for handling exceptional circumstances. In the above case you're clearly expecting n to possibly be > 5 so it's not really an exceptional circumstance. If there is a way for your application to de... |
4,105,255 | 4,105,315 | Why Can't I do this in C++? | Why the method getName() is wrong ?
#include <iostream.h>
#include <string.h>
class People
{
public:
char* getName();
void setName(char* n);
private:
char* name;
};
void People::setName(char* n)
{
name = new char(strlen(n));
strcpy(name,n);
}
char* People::getName()
{
return name;
}
| A couple of things here. Firstly, as Ignacio pointed out (assuming this was your question in the first place, it's a bit vague), we have private members so that other classes can't arbitrarily screw with them. We expose what we want other classes to use through a public interface.
Secondly, given that this is C++, I ... |
4,105,501 | 4,105,581 | How to set Visual Studio to work with only lib files? | so I have a Win32 consol project using libraries like openCV and FFmpeg (builds).
I have DLLs, .Libs, heders for tham all. How to set visual studio project not to use DLLs but only lib files?
| I assume you are talking about static libs and not using DLLs. If you have a dependency on static libs do this
Right click on your project -> Properties -> Linker -> General -> Additional Library Dependencies Specify your library directories.
Right click on your project -> Properties -> Linker -> Input -> Additional De... |
4,105,513 | 4,105,553 | Why is this Undefined Behavior? | Why does the following given expression invoke undefined behavior?
int i = 5;
i = (i,i++,i) + 1
My question is influenced by Als' question here
| It isn't undefined.
Answered here for C, Sequence points and partial order
I think the same applies in C++ (and here's my response before I saw that link):
The comma operator introduces a sequence point (and constrains to some extent the order in which the expression must be evaluated - left before right), so:
the two... |
4,105,534 | 4,105,908 | What EXIF lib can I use from a Qt program (on embedded linux)? | Can anybody recommend a nice exif lib for tiff img that can be used with a Qt program?
I would like to both read and write exif data.
Please note that that I need a license that is compatible with a closed source program,
so a lib that is using LGPL or a BSD style license would be really nice.
My first plan was to us... | Even if it is not Qt-related, probably your best option is the libexif C EXIF library. It is a GNOME core library (thus is widely deployed, tested and documented), still it is completely toolkit-agnostic, has no dependences and is LGPL licensed. It is a C library, thus its API is not idiomatic of Qt, nonetheless it is ... |
4,105,539 | 4,105,559 | What arguments must I pass to a function to perform an implicit construction of an object? | My apologies if this is a dupe. I found a number of posts re. preventing implicit conversions, but nothing re. encouraging implicit constructions.
If I have:
class Rect
{
public:
Rect( float x1, float y1, float x2, float y2){};
};
and the free function:
Rect Scale( const Rect & );
why would
Rect s = Scale( 137.0f... | Because the language does not support this feature. You have to write
Rect s = Scale(Rect(137.0f, 68.0f, 235.0f, 156.0f));
|
4,105,542 | 4,105,819 | Boost timer: how to get time when I need? | So I read this boost docs but I still do not see how to do such simple thing
int main() {
//stuff
startTimer();
// do stuff
int i =getTimerValue();
//stuff
}
so to get execution time of stuff that I've done. How to do such thing?
| Use boost::timer
#include <boost/timer.hpp>
int main() {
boost::timer t; // start timing
...
double elapsed_time = t.elapsed();
...
}
Note that the destuctor of a boost::progress_timer will display the time. So use scope if your aim is just to display time elapsed in the middle of a function.
int main() { ... |
4,105,672 | 4,105,709 | Importing Existing QT C++ Project with its own Makefile in Eclipse | I would like to import an C++ GUI Project with its own Makefile in Eclipse.
In the command prompt, everything works fine. But when I import the project, it gives an error
make all
make: *** No rule to make target `all'. Stop.
Would be glad, if you give me an idea where I am going wrong.
Thanks
Kiran
| How did you import the project? I have used Eclipse with existing makefile projects a couple of times by creating a new empty makefile project and overriding the location of the project to refer to where the Makefile is present. It warns that the directory already exists, but it works fine.
|
4,105,727 | 4,105,766 | C++: Stack is not unwound on exception thrown | Hallo,
I have a quite strange problem in one of my C++ projects:
I wrote a C++ Socket wrapper, that tries to connect to a given host and port (via IPv4/TCP) and throws a SocketException (derived from std::runtime_error), if an error occurs (e.g. 'Connection refused'). The exception is caught properly and an error me... | If your exception is thrown from the constructor, the destructor will not be called.
|
4,105,930 | 4,105,975 | Is using std::deque or std::priority_queue thread-safe? |
Possible Duplicates:
Is the C++ STL std::set thread-safe?
Thread safety for STL queue
I'm guessing it isn't, I just want to make sure.
meaning 2 threads using the same std::deque using std::deque::push_back or push_front at the same time.
Same question goes for std::priority_queue and the functions std::priority_que... | From Scott Myer's Effective STL Item 12. Have realistic expectations about the thread safety of STL containers
Multiple readers are safe. Multiple threads may simultaneously read the contents of a single container, and this will work correctly. Naturally, there must not be any writers acting on the container during th... |
4,106,052 | 4,106,092 | C++ strange segmentation fault by object creation | I have a strange problem by initiating a class object.
The problem is as strange as well not easily reproducible. However I will try to give an indicating example.
I have inheritance classes.
class BarClass {
public:
BarClass() {
...
}
BarClass(int i, int j) {
...
}
void doSomething() { ... }... | Your last issue first...
FooClass foo1();
does not create an object of type FooClass but declares a function called foo1() that takes no parameters and returns a FooClass. Remove the parentheses to create the instance as you did in the first code sample.
why you get a segmmentation fault may have something to do with... |
4,106,241 | 4,106,281 | sizeof returns different values for a struct when compiling different programs | I have 2 programs that share a header file. This header file defines a structure with a few members. There is then a #define: #define STRUCTURE_SIZE sizeof(OUR_STRUCTURE).
This structure is then used in shared memory with STRUCTURE_SIZE being used for the size argument to shmget().
Unfortunately, for the one program,... | A few possibilities:
you're compiling the two programs with different compilers and/or compiler switches
you have another header which appears before the header in question in one of the programs and this messes with #pragma pack or similar and doesn't restore the setting
a type that is used in the shared struct is de... |
4,106,362 | 4,107,245 | Messy function pointer interpretation | I happen to come across the following function pointer.
char (*(*x())[])();
It looks like an array of function pointer in the following format, but I can't see what f -> (*x()) means. How to interpret this messy function pointer?
char (*f[])();
ADDED
With John Bode's help, I make an example as follows.
#include <stdi... | My general procedure is to find the leftmost identifier in the declaration, and then work my way out, remembering that [] and () bind before * (i.e., *f() is normally parsed as *(f()) and *a[] is normally parsed as *(a[])).
So,
x -- x
x() -- is a function
*x() -... |
4,106,421 | 4,107,212 | Get all client headers in FastCGI (C/C++) | currently I am struggeling with a little problem:
I want create FastCGI/CGI binding for the nekoVM. This is done by writing some clue C/C++ code that is loaded by the VM. I want to make the behaviour of my binding as compatible as possible with neko native API (mod_neko, mod_tora). With mod_neko it is possible to get a... | You can use the externally-defined, null-terminated environ variable on most systems to get an array of all environment variables, which you could iterate to grab the headers you need (assuming FastCGI sets up the environment variables in a sensible way):
#include <stdio.h>
int main(int argc, char *argv[])
{
exter... |
4,106,444 | 4,106,465 | why is overloading needed when using operator<< via template? | As in this question, I'm experimenting to stream via a class using SBRM/RAII, so
SBRM(x) << "test";
could do some extra's in the destructor, but my template knowledge seems to be limited.
What I have (made simpler for clarity) is:
#include <iostream>
#include <sstream>
class SBRM
{
public:
SBRM(int j) : i(j) {}
~... | Because you’re expecting a non-const argument and literals can never be treated as such. Make the argument const and your troubles will go away:
template<typename T> SBRM& operator<<(T const& in) { oss << in; return *this; }
And as David has mentioned in his comment, you need overloads when using manipulators such as ... |
4,106,526 | 4,117,716 | Get Thread exit code after running ShellExecuteEx | How can the exit code of the main thread be retrieved, after having run ShellExecuteEx() in asychronous mode?
The process exit code can simply be retrieved as follows:
SHELLEXECUTEINFO execInfo;
execInfo.cbSize = sizeof(SHELLEXECUTEINFO);
execInfo.fMask = SEE_MASK_NOASYNC;
ShellExecuteEx(&execInfo);
/* Get process ex... | In order to get the exit code of the primary process thread - one has to obtain its HANDLE. Unfortunately ShellExecuteEx doesn't return you this (it returns only the HANDLE of the newly created process).
One could also enumerate all the threads in a particular process and open their handles (OpenThread). Thus, you coul... |
4,106,603 | 4,107,216 | Allowing multiple types of input for various forms of "yes" and "no" in C++ | I posted a question about how to get user input such as YES or NO to control the flow of a program using if else statements, I got a answer and now i'm a step closer to making this work, however another problem has arisen, i really need to allow for multiple inputs, for example this is what im trying:
if (input == ("YE... | Add the headers
#include <algorithm>
#include <cctype>
cout << "\nYES or NO" << endl;
string input ="";
cin >> input;
transform (input.begin(), input.end(), input.begin(),tolower);
if ( (std::string::npos != input.find( "yes" )) || (std::string::npos != input.find( "y" )) )
{
cout << "you said yes \n" ;
}
... |
4,106,655 | 4,106,676 | How large is the attributes can a class object hold? how to determine the stack/heap limit? | I have a class which requiring a large amount of memory.
class BigClass {
public:
BigClass() {
bf1[96000000-1] = 1;
}
double bf1[96000000];
};
I can only initiate the class by "new" a object in heap memory.
BigClass *c = new BigClass();
assert( c->bf1[96000000-1] == 1 );
delete c;
If I initiate it... | The stack have a fixed size that is dependant on the compiler options. See your compiler documentation to change the stack size for your executable.
Anyway, for big objects, prefer using new or better : smart pointers like shared_pointer (from boost or from std::tr1 or std:: if you have very recent compiler).
|
4,106,718 | 4,107,739 | anonymous empty untagged classes, structs, unions, and enums | !Disclaimer!: Please note that I am talking about untagged declarations. I know it's a possibly informal term and what I mean by it is that the declaration is not a typedef and it does not declare an object of the anonymous type. In these cases everything is clear.
Question 1:
which of the following is a well-formed C+... | None of it is legal. See [dcl.dcl] paragraph 3.
|
4,106,992 | 4,107,575 | Parallelize output using OpenMP | I've written a C++ app that has to process a lot of data. Using OpenMP I parallelized the processing phase quite well and, embarrassingly, found that the output writing is now the bottleneck. I decided to use a parallel for there as well, as the order in which I output items is irrelevant; they just need to be output a... | One way to get around output contention is to write the thread-local output to a string stream, (can be done in parallel) and then push the contents to cout (requires synchronization).
Something like this:
#pragma omp parallel for
for (i=0; i<n; i++) {
std::vector<MyData> related;
for (size_t j=0; j < data[i].s... |
4,107,076 | 4,107,203 | Rename MFC CArchive Serialized class | I'm using MFC's CArhive class to save off a project file for my app. One of the class names is wildly inaccurate and I'd like to change it, but simply changing the name everywhere renders previous archive files useless with an archive error. Is there a way to change the name of the archived class without rendering all ... | The crucial point is that when you use DECLARE_SERIAL and IMPLEMENT_SERIAL, a CRuntimeClass member is added to your class containing the name in its m_lpszClassName field.
This CRuntimeClass object is also added to a list maintained by the framework that is searched when classes are dynamically created.
You need to mak... |
4,107,087 | 4,107,256 | Accepting negative doubles with boost::program_options | I need to be able to have boost::program_options parse an array of doubles
that are passed on a command line. For positive doubles, this is no problem,
of course (use multitoken with std::vector<double> in add_options), but for
negative ones, I know that these are ambiguous arguments.
Here is a demonstration of what I... | The approach to handling negative numbers specified here might also work for you.
I was parsing it by the simple parser
store(command_line_parser(argc, argv).options(commands).run(), vm);
, but solution was to use the extended
one:
parse_command_line
|
4,107,145 | 4,107,179 | C++ polymorphism: Checking data type of sub class |
Possible Duplicate:
Finding the type of an object in C++
Hello,
I am sorry if it's a duplicate but I was not able to find answer to my question here.
Let's assume we have following class structure in c++:
class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=... | You can do this by checking if dynamic_cast<CRectangle*>(ptr) return non-null, where ptr is a pointer to CPolygon. However this requires the base class (CPolygon) to have at least one virtual member function which you probably need anyway (at least a virtual destructor).
|
4,107,315 | 4,107,326 | std::sort behavior with ints that are equal | What is the behavior of std::sort when used with ints that are equal is it going to keep them in the same order or just do some unpredictable stuff?
| std::sort doesn't preserve the order of the equivalent elements, std::stable_sort does. However, in case of int's you will not notice the difference unless you use some non-trivial ordering as in the following example:
struct half_less
{
bool operator()(int a, int b) const { return (a / 2) < (b / 2); }
};
std::sor... |
4,107,499 | 4,107,543 | How to determine when spawned process is ready? (Using CreateProcess() and FindWindow()) | This should be an easy one: I am creating a program that spawns a process using the win32 CreateProcess() function. Once this process is loaded, I find its window using FindWindow and send it messages using SendMessage(). The question is, how do I know when that window is ready to accept messages?
Consider the followin... | (Edit): User IInspectable pointed out problems with WaitForInputIdle(), and suggested CBT Hooks instead.
(...) callback function used with the SetWindowsHookEx
function. The system calls this function before activating,
creating, (...) a window; (... many other things).
Also, CBT is short for computer-based train... |
4,107,528 | 4,108,253 | Portable generation of a new file name in a specified directory | How can I portably (I am mostly interested in windows and linux) generate a new file name in a specified directory, with specified filename prefix and suffix?
std::string UniqueName(std::string const& dir, std::string const& prefix,
std::string const& suffix);
Any suggestions to implement this f... | Be aware that doing this wrong is a security hole. There are tricks to exploit temporary(ish) files, and these can give Administrator access to the whole system, not just your app. See this for some advice.
A couple of ways to do this:
Whenever possible, use library-provided functions instead of writing your own. For ... |
4,107,531 | 4,107,613 | Defining a static array of floats in C++ | I'm working on a planet generation tool in C++ and currently I'm trying to generate textures and heightmaps.
I'm using a 3d perlian noise function for this, so every time I generate a texture or heightmap I will calculate the value of the noise function for every vertex on the surface of the sphere.
These co ordinates ... | The method you describe is the best combination of efficiency and simplicity. If your compiler can't handle the entire array definition all at once, break the problem down into pieces. For example:
typedef float CubeFace[512][512][3];
CubeFace face1 = {etc};
...
CubeFace * textureMapSaved[6] = {&face1, &face2, &face3, ... |
4,107,571 | 4,107,586 | Unicode problem with linux g++ | I have problem with unicode functions under my Ubuntu 10.10 linux. Lot of unicode functions doesn't work correctly. When I try following simple code:
#include <wchar.h>
int main(int argc, char *argv[])
{
wprintf(L"test %s %s %s\n",L"one",L"two",L"three");
return 0;
}
and compile using g++ (gcc version 4.4.5 U... | You want %ls instead, as given in the wprintf(3) man page.
|
4,107,722 | 4,108,272 | Is there a workaround for the character limit on the Windows API function GetOpenFileName() when OFN_ALLOWMULTISELECT? | According to the MSDN documentation, the function GetOpenFileName() has no character limit with option OFN_ALLOWMULTISELECT when compiled for Unicode with Windows 2000 and greater. However, on Windows XP x64 SP2, I'm finding that the 32k ANSI limit is still in effect, despite the use of Unicode. I've seen other complai... | The documentation might be wrong. GetOpenFileName() is somewhat deprecated, and it no longer supports the latest Vista/Windows 7 features. What's even worse is that GetOpenFileName() pops up an Open dialog that looks like the one in Windows 95, at least when you try to customize the dialog with the LPOFNHOOKPROC featur... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.