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,501,737
2,501,791
Why does std::cout convert volatile pointers to bool?
If you try to cout a pointer to a volatile type, even a volatile char pointer where you would normally expect cout to print the string, you will instead simply get '1' (assuming the pointer is not null I think). I assume output stream operator<< is template specialized for volatile pointers, but my question is, why? Wh...
ostream::operator<< has the following overloads, among others: ostream& operator<< (bool val ); ostream& operator<< (const void* val ); When you pass in a volatile pointer, the second overload can't apply because volatile pointers cannot be converted to non-volatile without an explicit cast. However, any pointer can b...
2,501,745
2,501,761
Exception Specification
I know that this feature will be deprecated in C++0x, but for me as a total novice it seems like a good idea to have it. Could anyone explain to me why isn't a good idea?
Please see this detailed article by Herb Sutter. He has the most thorough explanation of the problems and short comings of their design. A Pragmatic Look at Exception Specificiations http://www.gotw.ca/publications/mill22.htm
2,501,776
2,501,783
Inline functions in C++
If we define a member function inside the class definition itself, is it necessarily treated inline or is it just a request to the compiler which it can ignore.
Yes, functions that are defined inside a class body are implicitly inline. (As with other functions declared inline it doesn't mean that the complier has to perform inline expansion in places where the function is called, it just enables the permitted relaxations of the "one definition rule", combined with the requirem...
2,501,957
2,502,251
subtract one image from another using openCV
How can I subtract one image from another using openCV? Ps.: I coudn't use the python implementation because I'll have to do it in C++
Use LoadImage to load your images into memory, then use the Sub method. This link contains some example code, if that will help: http://permalink.gmane.org/gmane.comp.lib.opencv/36167
2,501,968
2,501,997
Visual C++ Enable Console
I created an Empty Project in Visual C++, but now I need the Console to display debug output. How can I enable the Console without recreating the project or show the output in the VS output window?
You can always call AllocConsole in code to create a console for your application, and attach it to the process. FreeConsole will remove the console, detaching the process from it, as well. If you want all standard output stream data to go to the console, you need to also use SetStdHandle to redirect the output approp...
2,502,004
2,502,041
Undefined behavior on deleting char array trought void *
Is it true that the following yields undefined behavior: void * something = NULL; char * buffer = new char[10]; something = buffer; buffer = NULL; delete [] something; // undefined?? Do I first need to cast something to char * ?
Yes, strictly when you use delete[] the static type of the pointer that you delete[] must match the type of the array that you originally allocated or you get undefined behaviour. Typically, in many implementations, delete[] called on a void* which is actually an array of a type that has no non-trivial destructor works...
2,502,203
2,502,297
Can boost::asio only receive full UDP datagrams?
I am working on a UDP server built with boost::asio and I started from the tutorial customizing to my needs. When I call socket.receive_from(boost::asio::buffer(buf), remote, 0, error); it fills my buffer with data from the packet, but, if my understanding is correct, it drops any data that won't fit in the buffer. Sub...
This is not specific to boost; it's just how datagram sockets work. You have to specify the buffer size, and if the packet doesn't fit into the buffer, then it will be truncated and there is no way to recover the lost information. For example, the SNMP protocol specifies that: An implementation of this protocol need no...
2,502,232
2,502,263
Which programming languages support constant methods?
Which programming languages other than C++ support the concept of a constant class method? That is, what languages allow the programmer to constrain a method in such a way that it is guaranteed not to change the state of an object to which the method is applied? Please provide examples or references in your answer.
Haskell, since it's purely functional. Actually, every value/method is constant in Haskell even though mutable state/IO can be modelled through a mathematical construct called monad.
2,502,262
2,502,368
Profiling shared library/plugins written in C++ for Python?
I've got a C++ library that lets me write plugins in C++ and then automatically exposes them to python. I'm working on some networking stuff in a plugin and I'd like to profile it with something like gprof, but simply compiling with -pg and running the plugin via python doesn't generated the necessary profiling data. ...
I've found valgrind's cachegrind with KCachegrind to be helpful in analysis of un-prepared (e.g. no gprof code embedded) binaries.
2,502,314
2,502,350
Setting an std::string variable value from gdb?
Is it possible... when the debugger is stopped at a breakpoint, to modify the value of a std::string variable without resorting to hacks like tweaking the memory image of the current buffer? e.g. something like "set var mystring="hello world" ?
Try this (tested and works for me): call mystring.assign("hello world") The key is that instead of modifying memory directly, you call the object's functions to change its state. It so happens that std::basic_string has a member function called assign which does the job.
2,502,394
2,502,454
The cost of passing by shared_ptr
I use std::tr1::shared_ptr extensively throughout my application. This includes passing objects in as function arguments. Consider the following: class Dataset {...} void f( shared_ptr< Dataset const > pds ) {...} void g( shared_ptr< Dataset const > pds ) {...} ... While passing a dataset object around via shared_ptr...
Always pass your shared_ptr by const reference: void f(const shared_ptr<Dataset const>& pds) {...} void g(const shared_ptr<Dataset const>& pds) {...} Edit: Regarding the safety issues mentioned by others: When using shared_ptr heavily throughout an application, passing by value will take up a tremendous amount of t...
2,502,922
2,503,023
Preventing objects from being linked if they are not needed?
I have an ARM project that I'm building with make. I'm creating the list of object files to link based on the names of all of the .c and .cpp files in my source directory. However, I would like to exclude objects from being linked if they are never used. Will the linker exclude these objects from the .elf file automati...
If you are using RealView, it seems that it is possible. This section discusses it: 3.3.3 Unused section elimination Unused section elimination removes code that is never executed, or data that is not referred to by the code, from the final image. This optimization can be controlled by the --remove, --no_remove, --f...
2,503,024
2,503,046
How does one create a shared_ptr to pass to a function that takes a void *
That's pretty much it. I need to allocate memory and pass it to a function that takes a void *. I'd like to use a shared_ptr but I don't know how to do it.
Do you mean something like: boost::shared_ptr<int> myInt(new int(5)); call_some_function(myInt.get()); This only let's the function use the int*. It shouldn't try to delete it or take ownership. If you want just raw memory, use a vector: std::vector<char> memory(blockSize); call_some_function(&blockSize[0]); Again...
2,503,055
2,503,080
What is the best place to find software development conference listings?
I am interested in an array of software ideas and use more than one language, is there somewhere that concisely lists software development conferences year by year? I'd like to know what options are out there for this year and searching by ideology/language isn't practical in my opinion to get an overall. Some ideolog...
Not a listing but I use http://www.infoq.com/ to watch videos of past conferences.
2,503,103
2,503,180
What's the problem with the code below?
#include <iostream> #include <vector> using namespace std; int main(void) { int i, s, g; vector<int> a; cin >> s; for(i=1;i<=s;i++) { g = s; if(g<10) a.push_back(g); else { vector<int> temp; while(g > 0) { int k = g % 10; ...
Corrected code: int i, s, g; vector<int> a; cin >> s; for(i=1;i<=s;i++) { g = i; //Why was it s? if(g<10) a.push_back(g); else { vector<int> temp; while(g > 0) { int k = g % 10; g = g / 10; temp.push_back(k); //You need to push the remainder ...
2,503,222
2,503,500
Convert a code from FORTRAN to C
I have the following FORTRAN code which I need to convert to C or C++. I already tried using f2c, but it didn't work out. It has something to do with conversion from Lambert Conformal wind vector to a True-North oriented vector. Is anyone experienced in FORTRAN who could possibly help? PARAMETER ( ROTCON_P = 0.4226...
I speak Fortran as well as Tarzan speaks English, but this should be the gist of it in C: #include <math.h> const double ROTCON_P = 0.422618; const double LON_XX_P = -95.0; const double LAT_TAN_P = 25.0; int i, j, k; double angle2, sinx2, cosx2, ut, vt; double un[nzp_p][ny_p][nx_p]; double vn[nzp_p][ny_p][nx_p]; for...
2,503,269
2,503,303
Is this an acceptable use of "ASCII arithmetic"?
I've got a string value of the form 10123X123456 where 10 is the year, 123 is the day number within the year, and the rest is unique system-generated stuff. Under certain circumstances, I need to add 400 to the day number, so that the number above, for example, would become 10523X123456. My first idea was to substring ...
From the C++ standard, section 2.2.3: In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous. So yes, if you're guaranteed to never need a carry, you're good to go.
2,503,331
2,503,360
undefined reference linker error
I've stuck myself in a c++ project under linux ,for which I get an undefined reference when I try to create an object of a class that I just wrote.I believe this is an linker error caused by the fact that somewhere , somehow I should tell the linker to take into account the new class. I looked at the project properties...
Is your new source file included in the makefile for the project you're working on? (I'm guessing it's a makefile based on the shell script being names cmake.sh. If the script isn't using make, then the project description file will have a different name....)
2,503,533
2,503,542
How can I declare classes that refer to each other?
It's been a long time since I've done C++ and I'm running into some trouble with classes referencing each other. Right now I have something like: a.h class a { public: a(); bool skeletonfunc(b temp); }; b.h class b { public: b(); bool skeletonfunc(a temp); }; Since each one needs a reference to th...
You have to use Forward Declaration: a.h class b; class a { public: a(); bool skeletonfunc(b temp); } However, in many situations, this can force you to work with references or pointers in your method calls or member variables, since you can't have the full types in both class headers. If the size of the ty...
2,503,585
2,504,952
How is it possible to legally write ::: in C++ and ??? in C#?
These questions are a kind of game, and I did not find the solution for them. It is possible to write ::: in C++ without using quotes or anything like this and the compiler will accept it (macros are prohibited too). And the same is true for C# too, but in C#, you have to write ???. I think C++ will use the :: scope op...
You can write three consecutive question marks in C# without quotes, but not without whitespace, using the null-coalescing operator and the nullable alias character: object x = 0; int y = x as int? ?? 1;
2,503,807
2,503,845
Declaring an enum within a class
In the following code snippet, the Color enum is declared within the Car class in order to limit the scope of the enum and to try not to "pollute" the global namespace. class Car { public: enum Color { RED, BLUE, WHITE }; void SetColor( Car::Color color ) { _color = color; } ...
If Color is something that is specific to just Cars then that is the way you would limit its scope. If you are going to have another Color enum that other classes use then you might as well make it global (or at least outside Car). It makes no difference. If there is a global one then the local one is still used anywa...
2,503,939
2,504,044
How to create a array of boost matrices?
How can I define a array of boost matrices as a member variable? None of the following worked. boost::numeric::ublas::matrix<double> arrayM(1, 3)[arraySize]; boost::numeric::ublas::matrix<double>(1, 3) arrayM[arraySize]; boost::numeric::ublas::matrix<double> arrayM[arraySize](1, 3); Thanks, Ravi.
The size you initialize it with has nothing to do with the type. Therefore: // this makes things easier! typedef boost::numeric::ublas::matrix<double> matrix_type; // this is the type (no initialization) matrix_type arrayM[arraySize]; The problem comes with initializing the array. You can't do this: TheClass::TheClas...
2,504,161
2,504,852
Possible: Set Operations on Disparate Maps with Same Key Type?
Let's say I have two maps: typedef int Id; std::map<Id, std::string> idToStringMap; std::map<Id, double> idToDoubleMap; And let's say I would like to do a set operation on the keys of the two maps. Is there an easier way to do this than to create a custom "inserter" iterator? such that I could do something like: ...
My solution using iain's advice: template <typename T> class Select1st : public std::unary_function<T&,typename T::first_type> { public: int operator() (T & value) const { return value.first; } }; template <typename T> class KeyGrabItorAdapter : public boost::transform...
2,504,181
2,504,224
quiz ; does this compile and if so what does it return (I know the answer)
I found this typo recently: if (name.find('/' != string::npos)) Obviously the dev meant to type if(name.find('/') != string::npos) But I was amazed that to find that the error even compiles with -Wall -Werror (didnt try with -pedantic) So, coffee quiz: does it evaluate to true or false?
'/' doesn't equal string::npos since npos is required to be negative, and none of the characters in the basic execution character set is allowed to be negative. Therefore, it's going to look for a value of 1 in the string (presumably a string anyway) represented by name. That's a pretty unusual value to have in a strin...
2,504,253
2,516,231
C++ tool to generate random XML files from XML Schema?
I think there should be a tool to do so ? is anyone here aware of any ? I saw other posts related to this but found none for C++, I am aware that I can do that with JAVA and C#.
If you use XML Spy or oXygen, you can generate sample XML files based on a schema. Both tools accept commandline options and can be run in batch mode so that'll probably fit in your unit tests, if that's what you're after. Wrap your own C++ code around it and you're in business. If you need quality XML, with tons of tw...
2,504,496
2,504,508
What does "error: invalid function declaration" mean?
With GCC 4.1.2, I get the error tmp.cpp:8: error: invalid function declaration for the following code namespace edit { class A { public: void foo( ); }; } void edit:A::foo( ) { }
The problem was easy to fix: void edit:A::foo( ) { ^ missing ':' should be: void edit::A::foo( ) {
2,504,536
21,629,914
Why allow concatenation of string literals?
I was recently bitten by a subtle bug. char ** int2str = { "zero", // 0 "one", // 1 "two" // 2 "three",// 3 nullptr }; assert( int2str[1] == std::string("one") ); // passes assert( int2str[2] == std::string("two") ); // fails If you have godlike code review powers you'll notice I forgot the , after ...
I see several C and C++ answers but none of the really answer why or really what was the rationale for this feature? In C++ this is feature comes from C99 and we can find the rationale for this feature by going to Rationale for International Standard—Programming Languages—C section 6.4.5 String literals which says (emp...
2,504,562
2,504,572
Is it safe to define _HAS_TRADITIONAL_STL to enable STL functionality?
In attempting to use std::select1st from <functional> in a VS2008 project I found that it was ifdef'd out by a _HAS_TRADITIONAL_STL guard. Is there a reason for this? Is it safe to simply define _HAS_TRADITIONAL_STL before including <functional>?
The reason std::select1st is not present by default is that it is not part of the C++ standard library. It is one of the parts of the Standard Template Library (STL) that was not adopted into the C++ standard. I can't find any documentation on MSDN for _HAS_TRADITIONAL_STL, and it doesn't appear to be used in the vers...
2,504,814
2,504,876
How to launch a mac application without a terminal window
I've written an open-source c++ application and it works fine on Windows and Linux, I finally got a Mac Mini (with 10.5.8) so I've just been testing the Mac version. My application works fine when running it from inside a terminal window and typing ./appname , but if instead I double click on it from the finder, then i...
Mac binaries are set to be opened with the 'Terminal' program; there's no way around that, except by making a full application package, or have another program launch it via system or something like that. When double-clicking on a binary, the terminal window opens with ~ as the current directory. I suggest you use chdi...
2,504,825
2,505,012
Why does a multilanguage solution not work?
My solution has a C# application project C# User Controls project C++ Mathematics project One of the UserControls uses function from the Mathematics (C++ project). This UserControl is used in the application. Building and starting the application works just fine. When typing the IntelliSense suggests all the contain...
You can get BadImageFormatException when running a 32bit dll on a 64bit system. Try setting the target to "x86" on all your projects.
2,505,042
2,511,526
How to parse a tar file in C++
What I want to do is download a .tar file with multiple directories with 2 files each. The problem is I can't find a way to read the tar file without actually extracting the files (using tar). The perfect solution would be something like: #include <easytar> Tarfile tar("somefile.tar"); std::string currentFile, current...
I figured this out myself after a bit of work. The tar file spec actually tells you everything you need to know. First off, every file starts with a 512 byte header, so you can represent it with a char[512] or a char* pointing at somewhere in your larger char array (if you have the entire file loaded into one array for...
2,505,108
2,509,063
Error LNK1223 on ARM builds
eMbedded Visual C++ 3 project, that is building for PocketPC 2000. On the ARM build, the linker throws the following error: fatal error LNK1223: invalid or corrupt file: file contains invalid pdata contributions On SH3, the project compiles, links, and works. The project also works when built for ARM on Visual C++ 20...
Very weird. I tried commenting out everything in the file. The error went away when I commented out a function that was extern "C" void __declspec(naked) with no body (body #ifdef'fed away). I have similar functions in the project, but they did not throw any errors like this. Maybe a compiler bug...
2,505,240
2,505,247
Usage of std::string.append causes "Stack around the variable 'result' was corrupted"
I have the following code : std::string Utils::get() { std::string result; result.append(1, 'x'); result.append(1, 'x'); result.append(1, 'x'); return result; } I expect 'xxx' to be returned. However, when I run under debug mode, I get the warning "Stack around the variable 'result' was corrupted" ...
Your use of append is correct. Something else (possibly just before calling the function, etc.) is corrupting the stack. It's only when you use the stack some more (a function call in this case) will it detect it. The reason you won't see it in Release is because the function call is (likely) inlined. Ergo, the stack i...
2,505,257
2,505,263
Manage bad_alloc exception in C++ construtor
I have Java experience and recently am doing some C++ coding. My question is that if I have class A, in which I have to instantiate class B and class C as two of the member variables of A. If in the constructor of A, should I assume that allocations of class B and C never fail, and handle the bad allocation exception i...
If an exception is thrown during the construction of A, your destructor will not be called. Obviously the solution depends on what you're doing, but ideally you won't have to do any cleaning up. You should utilize RAII, and your class members should clean-up themselves. That is, don't use any pointers raw; wrap them up...
2,505,328
2,505,410
Calling class method through NULL class pointer
I have following code snippet: class ABC{ public: int a; void print(){cout<<"hello"<<endl;} }; int main(){ ABC *ptr = NULL: ptr->print(); return 0; } It runs successfully. Can someone explain it?
Under the hood most compilers will transform your class to something like this: struct _ABC_data{ int a ; }; // table of member functions void _ABC_print( _ABC_data* this ); where _ABC_data is a C-style struct and your call ptr->print(); will be transformed to: _ABC_print(nullptr) which is alright while ...
2,505,365
2,505,376
Compiler error: memset was not declared in this scope
I am trying to compile my C program in Ubuntu 9.10 (gcc 4.4.1). I am getting this error: Rect.cpp:344: error: ‘memset’ was not declared in this scope But the problem is I have already included in my cpp file: #include <stdio.h> #include <stdlib.h> And the same program compiles fine under Ubuntu 8.04 (gcc 4.2.4). Plea...
You should include <string.h> (or its C++ equivalent, <cstring>).
2,505,582
2,506,013
GCC exports decorated function name only from dll
I have a dll, it exports a function... extern "C" int __stdcall MP_GetFactory( gmpi::IMpUnknown** returnInterface ) { } I compile this with Code::Blocks GCC compiler (V3.4.5). Problem: resulting dll exports decorated function name... MP_GetFactory@4 This fails to load, should be plain old... MP_GetFactory I've resea...
Sorry to answer my own question, finally figured it out. Project/Build Options/Linker/Other Linker Options -Wl,--kill-at ...kills the decoration '@' symbol etc.
2,505,712
2,505,829
Trying to load a DLL with LoadLibrary and get R6034 "An application has made an attempt to load the C runtime library incorrectly"
I'm writing a wrapper program that loads Winamp input plugins. I've got it working well so far with quite a few plugins, but for some others, I get an error message at runtime when I attempt to call LoadLibrary on the plugin's DLL. (It seems to happen mostly with plugins that were included with Winamp.) A dialog app...
Starting from Visual Studio 2005, the C/C++ runtime MUST be put in the Windows side-by-side cache (C:\windows\WinSxS), so putting the CRT DLL's next to your exe doesn't work anymore (with one exception, see later). You MUST also refer to the CRT DLL's via a manifest file. This manifest file is generated by the linker ...
2,506,085
2,506,095
Overload dereference operator
I'm trying to overload the dereference operator, but compiling the following code results in the error 'initializing' : cannot convert from 'X' to 'int': struct X { void f() {} int operator*() const { return 5; } }; int main() { X* x = new X; int t = *x; delete x; return -898; } What am I doin...
You should apply dereference operator to a class type. In your code x has a pointer type. Write the following: int t = **x; or int t = x->operator*();
2,506,167
2,506,415
c++ macros with memory?
Is it possible to define macros write_foo(A); and read_foo(); so that: WRITE_FOO(hello); code_block_1; READ_FOO(); code_block_2; READ_FOO(); WRITE_FOO(world); code_block_3; READ_FOO(); code_block_4; READ_FOO(); expands into: code_block_1; hello; code_block_2; hello; code_boock_3; world; code_block_4; world...
Macros cannot redefine other macros, but you can do it manually. #define FOO hello FOO // expands to hello #undef FOO #define FOO world FOO // expands to world #undef FOO #define FOO blah FOO // expands to blah Unfortunately, the #define + #undef combination cannot be encapsulated in any other structure that I am...
2,506,632
2,506,644
C++ conditional compilation
I have the following code snippet: #ifdef DO_LOG #define log(p) record(p) #else #define log(p) #endif void record(char *data){ ..... ..... } Now if I call log("hello world") in my code and DO_LOG isn't defined, will the line be compiled, in other words will it eat up the memory for the string "hello world"? P.S. The...
This should be trivial to verify for yourself by inspecting the resulting binary. I would say "no", since the expression totally goes away, the compiler will never see the string (it's removed by the preprocessor's macro expansion).
2,506,793
2,506,800
C++: Life span of temporary arguments?
When creating a new instance of a MyClass as an argument to a function like so: class MyClass { MyClass(int a); }; myFunction(MyClass(42)); Does the standard make any guarantees on the timing of the destructor? Specifically, can I assume that it is going to be called before the next statement after the call to ...
Temporary objects are destroyed at the end of the full expression they're part of. A full expression is an expression that isn't a sub-expression of some other expression. Usually this means it ends at the ; (or ) for if, while, switch etc.) denoting the end of the statement. In your example, it's the end of the funct...
2,506,909
2,506,923
C++ error: expected initializer before ‘&’ token
the following piece of C++ code compiled two years ago in a suse 10.1 Linux machine. #ifndef DATA_H #define DATA_H #include <iostream> #include <iomanip> inline double sqr(double x) { return x*x; } enum Direction { X,Y,Z }; inline Direction next(const Direction d) { switch(d) { case X: return Y; case Y: re...
As everything in the C++ standard library, ostream lives in the std namespace, so it's std::ostream. I believe that, if this used to compile, this was in error.
2,507,364
2,507,380
return by reference - which of the two is the correct one
i have the function: const A& f(...) {...} a. const A a1 = f(..); b. const A &a2 = f(...); which of the is the better one to use? in both cases, if i understand correctly, i prevent the possibility of modifying the returned object. in the first option, the copy constructor of A will be called - am i correct?
It depends on what you want. In the first case you create a new const object that is constructed from the returned reference. It will be a snapshot of what was returned and will be valid for its entire lifetime. In the second you just initialize a reference. This means that any changes to the original object will be vi...
2,507,522
2,507,537
Porting C++-code from Windows to Unix: systemcalls colliding with name of functions
I'm porting some crufty C++ Windows-code to Linux, which uses functions called "open" and "close" inside every class... Very bad style, or? Luckily that wasn't a problem in windows, since their systemcalls are named different. When I try to call the systemcalls open() or close() I'm getting some compiler error about "n...
You can use ::open to refer to the open in the global namespace.
2,507,697
2,508,003
Is it "legal" for C++ runtime to call terminate() when the C++ code is used inside some non-C++ program?
In certain cases - especially when an exception escapes a destructor during stack unwinding - C++ runtime calls terminate() which must do something reasonable post-mortem and then exit the program. When a question "why so harsh" arises the answer is usually "there's nothing more reasonable to do in such error situatio...
Why is the C++ runtime calling terminate()? It doesn't do it at random, or due to circumstances which cannot be defined and/or avoided when the code is written. It does it because your code does something that is defined to result in a call to terminate(), such as throwing an exception from a destructor during stack un...
2,507,757
2,507,858
Hiding an entry from a QMenuBar in Qt4?
I can find no non-deprecated way of hiding an item in a menu bar in Qt4. This post: http://qt.nokia.com/developer/faqs/585 gives a method that uses deprecated Qt3 compatibility functions. Is there a better way?
QAction::setVisible() is what you are looking for: QAction* act = new QAction(tr("&Moo"), this); someMenu->addAction(act); // ... act->setVisible(false); To apply that to menus use their QAction* which you get either via QMenu::menuAction() or from QMenu::addMenu() (depending on what overload you use).
2,507,948
2,507,971
I need to randomize a number between two hex numbers, represented as strings
...and return the number as string. How can I do that? Is there any library for that?
You can use std::istringstring from <sstream> to convert the strings to integers. Then you can use rand or random to get a random number, which you can constrain to the interval using modular arithmetic, and then you can convert the number to a hexadecimal string using std::ostringstream. #include <sstream> #include <...
2,508,082
2,508,310
Recovering graceflly from a failed vsnprintf on msvc2008
I'm looking for a way to use some variant of vsnprintf() with a buffer that can possibly be longer than the input buffer without triggering an error to the user. So far I've found that vsnprintf() and its variants silently truncate the string when the buffer is too small but they don't return the actual length of the s...
The function you're looking for is _vscprintf (or _vscwprintf). These return the number of characters required without actually formatting anything.
2,508,284
2,508,377
C++ copy constructor and shallow copy
suppose I have a class with many explicit (statically allocated) members and few pointers that are allocated dynamically. When I declare a copy constructor in witch I make a deep copy of manually allocated members, I wouldn't like to copy each statically allocated member explicite. How can I use implicit (default) copy...
Use containment: class outer { public: outer( const outer& other ) : members_( other_.members_ ), pmember_( deep_copy( other.pmember_ )) {} // DON'T FORGET ABOUT THESE TOO outer& operator=( const outer& ); ~outer(); private: struct inner { inner( int i, float f )...
2,508,436
2,508,526
Fast sign in C++ float...are there any platform dependencies in this code?
Searching online, I have found the following routine for calculating the sign of a float in IEEE format. This could easily be extended to a double, too. // returns 1.0f for positive floats, -1.0f for negative floats, 0.0f for zero inline float fast_sign(float f) { if (((int&)f & 0x7FFFFFFF)==0) return 0.f; // test...
How do you think fabs() and fabsf() are implemented on your system, or for that matter comparisons with a constant 0? If it's not by bitwise ops, it's quite possibly because the compiler writers don't think that would be any faster. The portability problems with this code are: float and int might not have the same end...
2,508,529
2,508,568
C++ how to store integer into a binary file?
I've got a struct with 2 integers, and I want to store them in a binary file and read it again. Here is my code: static const char *ADMIN_FILE = "admin.bin"; struct pw { int a; int b; }; void main(){ pw* p = new pw(); pw* q = new pw(); std::ofstream fout(ADMIN_FILE, ios_base::out | ios_base::binary...
You probably want to flush fout before you read from it. To flush the stream, do the following: fout.flush(); The reason for this is that fstreams generally want to buffer the output as long as possible to reduce cost. To force the buffer to be emptied, you call flush on the stream.
2,508,605
2,508,659
Modifying a const through a non-const pointer
I'm a bit confused what happened in the following code: const int e = 2; int* w = ( int* ) &e; // (1) cast to remove const-ness *w = 5; // (2) cout &lt&lt *w &lt&lt endl; // (3) outputs 5 cout &lt&lt e &lt&lt endl; // (4) outputs 2 cout &lt&lt "w = " &lt&lt w ...
As I said in my comment, once you modified the const value you are in undefined behaviour land, so it doesn't make much sense to talk about what is happening. But what the hell.. cout << *w << endl; // (3) outputs 5 cout << e << endl; // (4) outputs 2 At a guess, *w is being evaluated at runtime...
2,508,796
2,508,814
C++ printf: newline (\n) from commandline argument
How print format string passed as argument ? example.cpp: #include <iostream> int main(int ac, char* av[]) { printf(av[1],"anything"); return 0; } try: example.exe "print this\non newline" output is: print this\non newline instead I want: print this on newline
No, do not do that! That is a very severe vulnerability. You should never accept format strings as input. If you would like to print a newline whenever you see a "\n", a better approach would be: #include <iostream> #include <cstdlib> int main(int argc, char* argv[]) { if ( argc != 2 ){ std::cerr << "Ex...
2,509,164
2,509,185
"Unhandled exception" error when using a loop inside thread
I got this error Unhandled exception at 0x0049b946 in Program.exe: 0xC0000005: Access violation reading location 0x00000090. and the error points to this line: // thread.hpp ln 56 void run() { f(); // here << } When trying to run this code: void frameFunc() { for(;;) ...
The code that you showed looks valid. I think the problem is inside the code that is not shown.
2,509,499
2,510,081
How to use std::allocator in my own container class
I am trying to write a container class which uses STL allocators. What I currently do is to have a private member std::allocator<T> alloc_; (this will later be templated so that the user can pick a different allocator) and then call T* ptr = alloc_.allocate(1,0); to get a pointer to a newly allocated 'T' object (and ...
Something you might want to do is have your own custom allocator that you can use to see how the standard containers interact wit allocators. Stephan T. Lavavej posted a nice, simple one called the mallocator. Drop it into a test program that uses various STL containers and you can easily see how the allocator is use...
2,509,668
2,509,680
Why using namespace std is necessary here?
#include <iostream> using namespace std; int main() { cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!! return 0; } If I remove the 2nd statement,the build will fail. Why is it necessary?
Because cout and endl are contained inside the std namespace. You could remove the using namespace std line and put instead std::cout and std::endl. Here is an example that should make namespaces clear: Stuff.h: namespace Peanuts { struct Nut { }; } namespace Hardware { struct Nut { }; } When you do some...
2,509,734
2,510,872
Break down C++ code size
I'm looking for a nice Stack Overflow-style answer to the first question in the old blog post C++ Code Size, which I'll repeat below: I’d really like some tool (ideally, g++ based) that shows me what parts of compiled/linked code are generated from what parts of C++ source code. For instance, to see whether a particul...
It does seem like something like this should exist, but I haven't used anything like it. I can tell you how I'd go about scripting this together, though. There are probably swifter and/or sexier ways to do it. First some stuff that you may already know: The addr2line command takes in an address and can tell you where t...
2,509,742
2,509,761
An array problem in C++
To access the array indice at the xth position we can use some sort of illustration as shown below #include<iostream> using namespace std; int main(){ float i[20]; for(int j=0;j<=20;j++) i[j]=0; } However the following piece of code does not work #include<iostream> using namespace std; float oldrand[...
new_random isn't declared as an array of floats, it's declared as a float. The compiler is trying to tell you you can't index into a float.
2,509,863
2,509,954
how to compile boost thread library
I want to compile only the thread and regular expresession library of boost and I want both static and dynamic libs. Could you please let us know how to do that?
You can use bjam to build libraries. Just invoke it in your boost folder. With parameters bjam toolset={your toolset} variant={release|debug} threading=multi link={static|shared} {library name} Just replace values from {} with values of your choice. For toolset name you can check {your boost dir}\tools\build\v...
2,509,969
2,519,104
Connect to an elevated COM server from a non-elevated process
We have a program which launches a child process that hosts a local COM server, which for various reasons must be launched elevated. Everything works fine so long as both the parent and the child process are elevated. However, we also want to run when the parent process is non-elevated. Launching the child process resu...
Read The COM Elevation Moniker for couple of ways to access elevated out-of-proc server.
2,509,970
2,509,990
Cannot find sleep function
i'm new at C Programming (i learned c++) i want to create a process with windows.h at first i just want to start my main programm that creates a process ( --> starts an other programm) that's my code, but it doesn't really work, i removed every unnessasery line of code but "void sleep(700)" (or "sleep (700)" for testin...
C (and C++) is case sensitive - sleep should be Sleep. Similar issues (and spelling) with your commented-out code.
2,510,089
2,521,772
How to monitor a directory for files in C++?
I need to monitor a directory which contains many files and a process reads and deletes the .txt files from the directory; once all the .txt files are consumed, the consuming process needs to be killed. How do I check if all the .txt files are consumed using C++? I am developing my application on Visual Studio on windo...
Since it was not required to perform action on each txt file deletion. I came up with following code: { intptr_t hFile; struct _finddata_t c_file; string searchSpec; for (size_t i = 0; i < dataPathVec.size(); ++i) { searchSpec = dataPathVec.at(i) + DIRECTORY_SEPERATOR + "*" + TXT_FILE_EXT; hFile = 0; ...
2,510,496
2,510,573
Exactly How Does My C++ Program Terminate When it Runs Out of Memory?
The following C++ program crashes on my Windows XP machine with a message "Abnormal program termination" class Thing {}; int main() { for (;;) new Thing(); } I would say it's an out of memory problem, except I'm not sure Windows gets near the limit. Is it Windows killing it on purpose? If so, how does it...
You're right it's an out-of-memory problem that causes your program to end. But it's not Windows that decides to end it with "Abnormal program termination". It's the C++ runtime ("msvcrt*.dll" on Windows) that raises the std::bad_alloc exception when new Thing fails to allocate memory. You can verify that with a simple...
2,510,521
2,510,568
How to handle 'this' pointer in constructor?
I have objects which create other child objects within their constructors, passing 'this' so the child can save a pointer back to its parent. I use boost::shared_ptr extensively in my programming as a safer alternative to std::auto_ptr or raw pointers. So the child would have code such as shared_ptr<Parent>, and boos...
Use a factory method to 2-phase construct & initialize your class, and then make the ctor & Init() function private. Then there's no way to create your object incorrectly. Just remember to keep the destructor public and to use a smart pointer: #include <memory> class BigObject { public: static std::tr1::shared_p...
2,510,888
2,510,909
binary_search not working for a vector<string>
#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; int main(void) { string temp; vector<string> encrypt, decrypt; int i,n, co=0; cin >> n; for(i=0;i<n;i++) { cin >> temp; encrypt.push_back(temp); } for(i=0;i<n;i++) { ...
Because the strings are not sorted in your vectors. Sort them first using std::sort.
2,511,312
2,511,380
Error handling and polymorphism
I have an application with some bunch of code like this: errCode = callMainSystem(); switch (errCode){ case FailErr: error("Err corresponding to val1\n"); case IgnoreErr: error("Err corresponding to val2\n"); ... ... default: error("Unknown error\n"); } The values are enum constants. Will it make s...
IMHO polymorphism would be overkill here, as you don't actually need different behaviour, only use different data per error code. I would use a simple map<ErrorCode, string> instead to store the mappings from error codes to messages. The polymorphic solution would require the extra overhead of creation and destruction ...
2,511,379
2,516,600
Vacancy Tracking Algorithm implementation in C++
I'm trying to use the vacancy tracking algorithm to perform transposition of multidimensional arrays in C++. The arrays come as void pointers so I'm using address manipulation to perform the copies. Basically, there is an algorithm that starts with an offset and works its way through the whole 1-d representation of ...
I found the best way which is about 12x faster than the set. I use a boost dynamic_bitset which lets me use the bitset and decide on the number of bits at runtime. Edit: In case anyone reads this in the future... this algorithm is not faster than a standard copy and write-back method of transposition with data element...
2,511,724
2,511,878
Error with swig: undefined symbol: _ZN7hosters11hostersLink7getLinkEi
I'm trying to make a python binding for the this library: http://code.google.com/p/hosterslib/. I'm using swig, heres is the code: %module pyhosters %{ #include "hosters/hosters.hpp" %} %include "hosters/hosters.hpp" I run swig -c++ -python -o swig_wrap.cxx swig.i and I compile with g++ -O2 -fPIC ...
That is the mangled name of: hosters::hostersLink::getLink(int) Make sure you have defined that function. Okay, I took a closer look at hosters 0.6. The header files declares two getLink methods: std::string getLink(void); std::string getLink(int n); But the source file only declares the first one: std::string hoste...
2,511,921
2,511,939
Which of these will create a null pointer?
The standard says that dereferencing the null pointer leads to undefined behaviour. But what is "the null pointer"? In the following code, what we call "the null pointer": struct X { static X* get() { return reinterpret_cast<X*>(1); } void f() { } }; int main() { X* x = 0; (*x).f(); // the null pointer? (1) ...
Only the first and the last are null pointers. The others are results of reinterpret_cast and thus operate on implementation defined pointer values. Whether the behavior is undefined for them depends on whether there is an object at the address you casted to.
2,512,371
2,512,585
Extracting, then passing raw data into another class - How to avoid copying twice while maintaining encapsulation?
Consider a class Book with a stl container of class Page. each Page holds a screenshot, like page10.jpg in raw vector<char> form. A Book is opened with a path to a zip, rar, or directory containing these screenshots, and uses respective methods of extracting the raw data, like ifstream inFile.read(buffer, size);, or un...
In terms of code changes based on what you have already, the simplest is probably to give Page a setter taking a non-const vector reference or pointer, and swap it with the vector contained in the Page. The caller will be left holding an empty vector, but since the problem is excessive copying, presumably the caller do...
2,512,478
2,512,615
Will the following program cause any problem during compiling and execution process?
Will the following program cause any problem during compiling and execution process? class A{ public: virtual void foo(){} }; class B:public A{}; int main(){ B b; b.foo(); }
There will be no problems compiling or running this program. virtual functions can be overridden, but they don't have to be. If an object's class does not implement the virtual function, then the superclass will be checked for an implementation.
2,512,492
2,512,540
Why am I getting a segmentation fault?
If I pass a value greater than 100 as the second argument to BinaryInsertionSort, I get a segmentation fault. int BinarySearch (int a[], int low, int high, int key) { int mid; if (low == high) return low; mid = low + ((high - low) / 2); if (key > a[mid]) return BinarySearch (a, mid + ...
You are passing an array a[] in. it must be large enough that the values hi and low are in range. For example, if you pass an array of size 1 in, and low = 0. hi = 2, then mid = 1 which will be out of range (an array of size 1 can only have a[0] dereferenced, a[1] will be out of range).
2,512,512
2,512,527
Ambiguous call to Overloaded Function (const variety)
How do I fix this error? error C2668: 'std::_Tree<_Traits>::end' : ambiguous call to overloaded function My code looks like this: typedef map<int const *, float> my_map_t; my_map_t _test; my_map_t::const_iterator not_found = my_map_t::end(); if (_test.find(&iKeyValue) == not_found) { _test[iKeyValue] = 4 + 5; // ...
From your code, it appears that my_map_t::end() is static (otherwise you'd have to call it on an instance, e.g. _test.end()). Edit: Jesse Beder is right in his comment to the question; the code doesn't make much sense, since _test is a type, not an object. Static member functions cannot be const-qualified (the const-...
2,512,528
2,512,792
FORTRAN function returning an array causes a segfault (calling from C++)
Basically, here's my problem. I'm calling someone else's FORTRAN functions from my C++ code, and it's giving me headaches. Some code: function c_error_message() character(len = 255) :: c_error_message errmsg(1:9) = 'ERROR MSG' return end That's the FORTRAN function. My first question is: Is there anything in there tha...
Here is a method that works. When I tried to use the ISO C Binding with a function returning a string, the compiler objected. So if instead you use a subroutine argument: subroutine fort_err_message (c_error_message) bind (C, name="fort_err_message") use iso_c_binding, only: C_CHAR, C_NULL_CHAR character (len=1, ki...
2,512,551
2,535,401
winHTTP GET request C++
I'll get right to the point. This is what a browser request looks like GET /index.html HTTP/1.1 This is what winHTTP does GET http://site.com/index.html HTTP/1.1 Is there any I can get the winHTTP request to be the same format as the regular one? I'm using VC++ 2008 if it makes any difference
Your code should look like this: // Specify an HTTP server. if (hSession) hConnect = WinHttpConnect( hSession, L"www.example.com", INTERNET_DEFAULT_HTTP_PORT, 0); // Create an HTTP request handle. if (hConnect) hRequest = WinHttpOpenRequest( hConnect, L"GET", L"/path/resource.htm...
2,512,588
2,512,697
A method to change effective user id of a running program?
I'm writing a simple package manager and I'd like to automatically try sudo if the program isn't run as root. I found a function called seteuid, which looks likes it's exactly what I need, but I don't have the permissions to run it. So far all I can think of is a bash script to check before they get to the actual binar...
As bmargulies says in his answer, you can do this if you binary is owned by root and has the setuid bit set - but then you will need to implement the authentication part (checking that the user is actually allowed to become root) yourself too. You'd be essentially rewriting sudo within your application - the best way t...
2,512,691
2,512,714
How to use references, avoid header bloat, and delay initialization?
I was browsing for an alternative to using so many shared_ptrs, and found an excellent reply in a comment section: Do you really need shared ownership? If you stop and think for a few minutes, I'm sure you can pinpoint one owner of the object, and a number of users of it, that will only ever use it during th...
You can use a shared_ptr ( or any smart pointer, or even a dumb pointer) but not have shared ownership. E.g. class Foo; class FooManager { private: shared_ptr<Foo> foo; public: Foo& getFoo() { return *foo; } }; (This is just a sketch - you still need a setFoo(), and perhaps getFoo() should return a Foo *....
2,512,740
2,512,788
Hopping from a C++ to a Perl/Unix job
I have been a C++ / Linux Developer till now and I am adept in this stack. Of late I have been getting opportunities that require Perl, Unix (with knowledge of C++,shell scripting) expertise. Organizations are showing interest even though I don't have much scripting experience to boast off. The role is more in a Suppor...
Regarding changing of stack, it definitely helps you long term in your career, both from extra experience available to offer to next employer to expanded job set you can qualify for to increased programming IQ due to knowing different points of view (e.g. Perl, for all its scripting origins, when used properly, has bo...
2,512,746
2,512,769
In C++, do variadic functions (those with ... at the end of the parameter list) necessarily follow the __cdecl calling convention?
I know that __stdcall functions can't have ellipses, but I want to be sure there are no platforms that support the stdarg.h functions for calling conventions other than __cdecl or __stdcall.
The calling convention has to be one where the caller clears the arguments from the stack (because the callee doesn't know what will be passed). That doesn't necessarily correspond to what Microsoft calls "__cdecl" though. Just for example, on a SPARC, it'll normally pass the arguments in registers, because that's how ...
2,512,823
2,512,879
How to include only BOOST smart pointer codes into a project?
What are best practices to include boost smart pointer library only without adding all boost libraries into the project? I only want boost smart pointer library in my project and I don't want to check in/commit 200 MB source codes (boost 1.42.0) into my project repository just for that. What more, my windows mobile pro...
For just the smart pointer library, you have two options. Copy the headers you include in your source files (shared_ptr.hpp, etc.). Then copy over additional files until the project builds (make sure to maintain the directory structure). Use the boost bcp utility. For larger subsets, this tool saves a ton of time. Th...
2,512,931
2,512,970
Catch Multiple Custom Exceptions? - C++
I'm a student in my first C++ programming class, and I'm working on a project where we have to create multiple custom exception classes, and then in one of our event handlers, use a try/catch block to handle them appropriately. My question is: How do I catch my multiple custom exceptions in my try/catch block? GetMessa...
If you have multiple exception types, and assuming there's a hierarchy of exceptions (and all derived publicly from some subclass of std::exception,) start from the most specific and continue to more general: try { // throws something } catch ( const MostSpecificException& e ) { // handle custom exception } cat...
2,512,978
2,512,979
How to delete duplicate vectors within a multidimensional vector?
I have a vector of vectors: vector< vector<int> > BigVec; It contains an arbitrary number of vectors, each of an arbitrary size. I want to delete not duplicate elements of each vector, but any vectors that are the exact same as another. I don't need to preserve the order of the vectors so I can sort etc.. It should be...
Why not use unique? I think if you're having problems getting it to work it's because using std::unique requires that the range be sorted. So, something like std::vector<std::vector<int>> myVec; std::sort(myVec.begin(), myVec.end()); myVec.erase(std::unique(myVec.begin(), myVec.end()), myVec.end());
2,513,036
2,513,103
confusing fork system call
i was just checking the behaviour of fork system call and i found it very confusing. i saw in a website that Unix will make an exact copy of the parent's address space and give it to the child. Therefore, the parent and child processes have separate address spaces #include <stdio.h> #include <sys/types.h> int main(vo...
Basically the concept of virtual memory gives a view to the process as if it is the sole owner of the system. It feels it has access to the complete memory. But in reality, the OS gives it only a virtual memory which is mapped to the actual memory by the OS by using MMU. So, what happens in your case is, each process (...
2,513,108
2,513,117
How does extern work in c++?
This is from the <iostream>: namespace std { extern istream cin; ///< Linked to standard input extern ostream cout; ... It seems by using extern the data types defined in other namespaces will just be available?
extern is used to refer to a variable defined in a different compilation unit (for now, you can think of a compilation unit as a .cpp file). The statements in your example declare rather than define cin and cout. It is telling the compiler that the definition of these objects is found in another compilation unit (whe...
2,513,138
2,520,958
ctrl+alt+del disable using c in window OS
How to disable ctrl+alt+del using C in Window OS? I tried SystemParametersInfo(SPI_SETSCREENSAVERRUNNING, true, &bOldState, 0); but it doesn't working for me. Can you kindly guide me, so that I can make it possible.
The SPI_SETSCREENSAVERRUNNING parameter you are using is designed for screensavers on Windows 95. It works on Windows 95/98/ME and earlier. It does not work on Windows NT/2000/XP/Vista. The Ctrl-Alt-Del Hotkey combo can be disabled on Windows NT/2000/XP/Vista, but not usually from an application (user mode). Here ar...
2,513,151
2,513,168
Prossess state getting in c under window plateform
I am using CreateProcess function for creating the process, is there any option to get the current state of the process (running or not). Kindly guide me how can I make it possible.
Use OpenProcess function with that dwProcessId if it returns NULL Process is not running otherwise it will return handle to that process
2,513,228
2,513,302
Using glRotate and glTranslate with collision detection
Say I use glRotate to translate the current view based on some arbitrary user input (i.e, if key left is pressed then rtri+=2.5f) glRotatef(rtri,0.0f,1.0f,0.0f); Then I draw the triangle in the rotated position: glBegin(GL_TRIANGLES); // Drawing Using Triangles glVertex3f( 0.0f, 1.0f, 0.0f); // Top glVertex3...
The objects you use for collision detection are usually not the objects you use for display. They are usually simpler and faster. So yes, the way to do it is to maintain the transformation you're using manually but you wouldn't be doubling up the work because the objects are different.
2,513,239
2,513,360
does XMLDOMNodePtr::get_text() needs to be deallocated explicitly?
Greetings, Would like to know if we need to explicitly free the string allocated by a xmldomnodeptr using it's get_text() i.e. IXMLDOMNodePtr pNode; /*some code*/ BSTR sValue; pNode->get_text(&sValue); /*Should I do this?*/ SysFreeString(sValue); I cannot see any documentation stating the same...
yes. You will have to free the string. BSTR bstrItemText = NULL; pIDOMNode->get_text(&bstrItemText); //Discl: return value is not checked here... if(bstrItemText) { ::SysFreeString(bstrItemText); bstrItemText = NULL; }
2,513,312
2,515,061
NUnit does not capture output of std::cerr
I have an nunit Test in C#, that calls a C# wrapper of a function in a C++ DLL. The C++ code uses std::cerr to output various messages. These messages cannot be redirected using nunit-console /out /err or /xml switch. In nunit (the GUI version) the output does not appear anywhere. I would like to be able to see this ou...
Redirecting std::cerr is a matter of replacing the stream buffer with your own. It is important to restore in original buffer before we exit. I don't know what your wrapper looks like, but you can probably figure out how to make it read output.str(). #include <iostream> #include <sstream> #include <cassert> using name...
2,513,403
2,680,920
C++ Adobe Premiere video filter - print/draw/render text in output video frame
I want to write video filter for Adobe Premiere, and I need to print/draw/render some text into the output video frame. Looking into adobe premiere cs4 sdk I couldn't find a quick answer - is it possible? Please provide some samples! Thanks!
Some strategy I will try to implement: draw text with GDI into bitmap of frame size (VideoHandle->piSuites->ppixFuncs->ppixGetBounds) overlap frame pixels (VideoHandle->source) with bitmap pixels UPDATE alt text http://img413.imageshack.us/img413/6201/adobe.jpg Working sample, using Simple_Video_Filter sample from ...
2,513,502
2,513,568
Disable All I/O Ports on a Windows PC Using C?
Is it possible to disable all the I/O ports of the Windows PC my program is running on? If so, can that be done using C? The goal is that the user should not be able to interact with the PC through any path except for the network card while my program is running.
I doubt it's possible, and if it was you wouldn't want to do it anyway. First of, quite a few I/O ports are used for communication within the computer itself, so if you could disable them all, the computer would quickly quit working. The network adapter normally uses at least a couple, so if you did it, the network wou...
2,513,505
26,639,774
How to get available memory C++/g++?
I want to allocate my buffers according to memory available. Such that, when I do processing and memory usage goes up, but still remains in available memory limits. Is there a way to get available memory (I don't know will virtual or physical memory status will make any difference ?). Method has to be platform Independ...
Having read through these answers I'm astonished that so many take the stance that OP's computer memory belongs to others. It's his computer and his memory to do with as he sees fit, even if it breaks other systems taking a claim it. It's an interesting question. On a more primitive system I had memavail() which would ...
2,513,525
2,513,659
bitwise not operator
Why bitwise operation (~0); prints -1 ? In binary , not 0 should be 1 . why ?
You are actually quite close. In binary , not 0 should be 1 Yes, this is absolutely correct when we're talking about one bit. HOWEVER, an int whose value is 0 is actually 32 bits of all zeroes! ~ inverts all 32 zeroes to 32 ones. System.out.println(Integer.toBinaryString(~0)); // prints "1111111111111111111111111111...
2,513,741
2,513,767
C vs. C++ for performance in memory allocation
I am planning to participate in development of a code written in C language for Monte Carlo analysis of complex problems. This codes allocates huge data arrays in memory to speed up its performance, therefore the author of the code has chosen C instead of C++ claiming that one can make faster and more reliable (concern...
Definitely C++. By default, there's no significant difference between the two, but C++ provides a couple of things C doesn't: constructors/destructors. These let you automate most memory management, improving reliability. per-class allocators. These let you optimize allocation based on how particular objects are desig...
2,513,897
2,513,937
How can I handle weird errors from calculating acos / sin / atan2?
Has anyone seen this weird value while handling sin / cos/ tan / acos.. math stuff? ===THE WEIRD VALUE=== -1.#IND00 ===================== void inverse_pos(double x, double y, double& theta_one, double& theta_two) { // Assume that L1 = 350 and L2 = 250 double B = sqrt(x*x + y*y); double angle_beta = atan2...
The "weird value" is NaN (not a number). The problem is because (L2*L2 - B*B - L1*L1) / (-2*B*L1) = 6.08112… is outside of the range [-1, 1] where acos is well-defined for real numbers. So NaN is returned. Are you sure the formula is correct? If you want to catch an NaN, the NaN needs to be a signaling NaN. For gcc, c...
2,513,988
2,514,298
Iteration through std containers in openmp
I'm trying to use openmp to multithread a loop through std::set. When I write the following code - #pragma omp parallel for for (std::set<A>::const_iterator i = s.begin(); i != s.end(); ++i) { const A a = *i; operate(a); } I get this error: error: invalid type for iteration variabl...
Loop parallelization for stl iterators only works since OpenMP 3.0, and only for random access iterators (e.g. vector and deque). You should be able to do something like this: #pragma omp parallel { for (std::set<A>::const_iterator i = s.begin(); i != s.end(); ++i) { #pragma omp single nowait { operat...
2,514,050
2,514,358
How to update a uniform variable in GLSL
I am trying to get update the eye position in my shader from my appliaction but I keep getting error 1281 when I attempt this. I have no problems after the initialization just when i subsequently try to update the values. Here is my code: void GraphicsObject::SendShadersDDS(char vertFile [], char fragFile [], ...
It is most likely this is caused by the fact that EyePos is invalid. What happens if you change the function to the following? void GraphicsObject::UpdateEyePosition(Vector3d& eyePosition) { EyePos = glGetUniformLocation(program, "EyePosition"); glUniform4f(EyePos, eyePosition.X(),eyePosition.Y(), eyePosition.Z...
2,514,086
2,514,764
Run codes for only 60 times each second
I'm creating a directx application that relies on the system time (because it must be accurate), and I need to run lines of code for 60 times each second in the background (in a thread created by boost::thread). that's equal to 60 FPS (frame per second), but without depending on the main application frame rate. //........
Since 60 Hz is a common monitor refresh rate, it sounds like you want to enable V-Sync, instead of messing around with timers and sleeps. You mentioned you're using DirectX - If you're using DirectX 9, specify D3DPRESENT_INTERVAL_ONE when creating the device, and the application will synchronize to the monitor refresh ...
2,514,090
2,514,117
How to modify Registry of window OS from c or c++
I want to modify the registry of window OS using c. kindly guide me or give me some hints so that I can make it possible.
You need to use Win32 APIs such as RegOpenKeyEx for doing this.