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
3,431,735
3,431,811
C++ standard, overloaded function resolution/matching
Does C++ standard guarantee the following?: template<typename T> void function(T (&)[1]); template<typename T> void function(T*); int a[1]; function(a); // first function gets called, not second version
Yes, this is guaranteed, but the reason is different than what GMan says. The "array of length 1" overload will be selected because it is more specialized than the second in template functions partial order. Basically, it means that an argument in the form T(&)[1] will always match the second template argument in the f...
3,431,855
3,431,866
testing if a shared_ptr is NULL
I have the following code snippet: std::vector< boost::shared_ptr<Foo> >::iterator it; it = returnsAnIterator(); // often, it will point to a shared_ptr that is NULL, and I want to test for that if(*it) { // do stuff } else // do other stuff Am I testing correctly? The boost docs say that a shared_ptr can be impl...
Yes, you are testing it correctly. Your problem, however, is likely caused by dereferencing an invalid iterator. Check that returnsAnIterator() always returns an iterator that is not vector.end() and the vector is not modified in between, or empty.
3,431,998
3,445,632
A small lisp like DSL that gets compiled into C/C++ code -- Antlr a good choice?
Creating a Lisp syntax like DSL - very small specific application - but very fast - code generation in C, Antlr a good choice? It is necessary for many reasons that it be very fast and it will internally call a lot of C++ APIs, hence I cannot write it in a language other than C/C++. The last time I did something in co...
ANTLR is good when your syntax is complex. LISP syntax is not complex, by design. Everything is pretty much handled by two grammar rules: sexp = identifier | number | string | '(' sexps ')' ; sexps = empty | sexps sexp ; Its such a simple lexer and parser that you can easily implement this as a recursive descent par...
3,432,039
3,432,049
C++0x "Hello Concurrent World" immediately segfaults on g++/linux?
Browsing through a Currency in C++0x book and thought I would give the sample code a run. It is as basic as it gets. #include <iostream> #include <thread> void hello() { std::cout<<"Hello Concurrent World\n"; } int main(int argc, char *argv[]) { std::thread t(hello); t.join(); } Compiled with: g++ -st...
You need to compile/link using the -pthread flag.
3,432,186
3,435,686
Registering XPCOM in firefox. Unknown CID
I'm having difficulties registering an example XPCOM component into firefox from this example here: http://www.iosart.com/firefox/xpcom/ I'm trying this on Firefox 3.6. After successfully building and transferring the XPT and library into the components folder in firefox, and following what instructions are applicable,...
See the first bullet point here. This method of adding components to Firefox no longer works in Firefox 3.6.
3,432,225
3,432,237
"unresolved external symbol" on template specialization for array of char
I have something like this in my code: template <typename T> struct A { void Print(); }; template <> struct A<char*> { void Print() { printf("Char*!\n"); } }; template <typename T> void DoSomething(T& lol) { A<T> a; a.Print(); } int main() { char a[5]; DoSomething(a); } And this produces the following l...
a does not have type char*, it has type char[5], so the primary template is instantiated, not the specialization. If you manually perform the array-to-pointer conversion, it will use the specialization: char a[5]; char* aptr = a; DoSomething(a); If you don't want the primary template to be used for a char array, you c...
3,432,231
3,441,124
Calling lua functions from .lua's using handles?
I'm working on a small project trying to integrate lua with c++. My problem however is as follows: I have multiple lua scripts, lets call them s1.lua s2.lua and s3.lua. Each of these has the following functions: setVars() and executeResults(). Now I am able to to call a lua file through LuaL_dofile and immediately afte...
This is effectively what gwell proposed using the C API: #include <stdio.h> #include "lua.h" static void executescript(lua_State *L, const char *filename, const char *function) { /* retrieve the environment from the resgistry */ lua_getfield(L, LUA_REGISTRYINDEX, filename); /* get the desired function fr...
3,432,457
3,432,538
c++ win32 output a text
im using visual studio c++ 2008 i created project that contents the full window code. i don't know how to output text to window. i mean i have full functional window with menu bar and under the menu bar there is the body im trying to ouput the text in the body but how?
This page has a sample on how to do it in Win32: http://www.rohitab.com/discuss/index.php?showtopic=11454 The code below is the Window Procedure for the window, if you note the WM_PAINT (That is the message that tells the window to paint itself) the code is simply drawing the text to the Device Context, which is the cl...
3,432,478
3,432,499
Are literal numbers treated as constants?
It is always better for contants such as PI to #define them or declare them const so the compiler can optimize and it becomes less error prone. I was wondering however, how are literal numbers in statements treated? Ex: float x; const int y = 60; x = y / 3.0f; In this example how would 3.0f be treated? Would it inheri...
What optimizations will take place depends on the compiler. In your case, both C and C++ compilers will normally have enough information to optimize your source code into identical machine code. In other words, it doesn't really depend much on what is literal and what is constant in this code. Having said that, the mea...
3,432,576
3,432,583
Can a private variable be accessed through its address?
Would it be possible for a public function to return a pointer to a private variable in the class. If so / if not, what would happen? would it crash or is there anything highly unsafe about this? Can the pointed data be read or written to? Thanks
Yes, a member function may return a pointer (or reference) to a private data member. There is nothing wrong with this except that in most circumstances it breaks encapsulation. The data member can certainly be read via the returned pointer or reference. Whether or not it can be written to depends on whether the retur...
3,432,587
3,432,598
Concatenating qt-specific keyword and macro argument with a space in between
My problem is quite simple. I want the following macro #define PROXYPASS(name, param) \ void MyClass::sl_name(param _param) { \ emit name(_param); \ } to expand PROXYPASS(clientAdded, Client*) to: void MyClass::sl_clientAdded(Client* _param) { \ emit clientAdded(_param); \ } but since it ain't working i.e. it...
Just put nothing there, you don't need to concatenate anything: #define PROXYPASS(name, param) \ void MyClass::sl_ ## name(param _param) { \ emit name(_param); \ }
3,432,609
3,432,640
Why does `myvector.push_back(autoPtr.release())` provide the strong exception safety guarantee?
EDIT: I should've mentioned, I was looking at the documentation for Boost's ptr_sequence_adapter and it claims that their adapter for template< class U > void push_back( ::std::auto_ptr<U> x ); is equivalent to doing vec.push_back(autoPtr.release()); and also provides the strong exception guarantee. And then I realize...
This is specifically a feature of the Boost pointer containers library. The base push_back member function is defined as: void push_back( value_type x ) // strong { this->enforce_null_policy( x, "Null pointer in 'push_back()'" ); auto_type ptr( x ); // notrow this->base().push_bac...
3,432,760
3,432,766
How does one remove duplicate elements in place in an array in O(n) in C or C++?
Is there any method to remove the duplicate elements in an array in place in C/C++ in O(n)? Suppose elements are a[5]={1,2,2,3,4} then resulting array should contain {1,2,3,4} The solution can be achieved using two for loops but that would be O(n^2) I believe.
If, and only if, the source array is sorted, this can be done in linear time: std::unique(a, a + 5); //Returns a pointer to the new logical end of a. Otherwise you'll have to sort first, which is (99.999% of the time) n lg n.
3,433,088
3,433,117
How to create a .desktop file application launcher on Linux?
I've developed an application in Qt which uses a launch script, myapp.sh. I've created a .desktop file which launches this script, and set: Command: $PWD/myapp.sh Work path: $PWD However, $PWD prints my home directory when I launch the .desktop file, resulting in attempting to launch ~/myapp.sh rather than ~/Developmen...
$PWD holds the current working directory of the shell, which has nothing to do with the location of the .desktop file.. One way you can do this is with: Exec=$(dirname %k)/myapp.sh From the spec, %k is "The location of the desktop file as either a URI (if for example gotten from the vfolder system) or a local filenam...
3,433,185
3,951,978
Getting an Xcode project's resources in c++
I'm coding a simple game using SFML in Xcode. I have a .png of a block I want to use in a sprite. At the moment, I have to type the full path to the image in the code snippet below: sf::Image blockImage; if (!blockImage.LoadFromFile("/Users/me/Development/Tetris/images/block.png")) { cerr << "Could not load block ...
Your question isn't exactly clear, but I'll try to explain as best I can: As far as the OS is concerned, Resources is just a folder inside a application bundle, the only thing special about it is that when an application starts, the Resources folder is the default file path (called the working directory). This means if...
3,433,464
3,433,526
scanf() with C++ enums
The following is a typical situation in our codebase. enum ConfigOption { CONFIG_1=1, CONFIG_2=2, CONFIG_3=3 } ConfigOption cfg1, cfg2; sscanf(s, "%d", &cfg1); This is an internally used simulation software. Not distributed. Ease of maintenance and correctness are important. Portability and user interface -- not re...
If you have a modern compiler like vs2010 you can specify the size of the enum elements enum class ConfigOption: unsigned int {CONFIG_1=1, CONFIG_2=2, CONFIG_3=3}; its new in C++0x
3,433,520
3,745,123
What can I do to avoid TCP Zero Window/ TCP Window Full on the receiver side?
I have a small application which sends files over the network to an agent located on a Windows OS. When this application runs on Windows, everything works fine, the communication is OK and the files are all copied successfully. But, when this application runs on Linux (RedHat 5.3, the receiver is still Windows) - I see...
I tried to disable Nagle's algorithm (with TCP_NODELAY), and somehow, it helped. Transfer rate is much higher, TCP window size isn't being full or reset. The strange thing is that when I chaged the window size it didn't have any impact. Thank you.
3,433,845
3,433,930
Windows Logoff Event c++
I need to catch windows logoff event, I'm using c++. I dont know where to start searching, thanks for any help, Dani.
In console application, you can register a callback (SetConsoleCtrlHandler, CTRL_LOGOFF_EVENT). In message-loop application, you can catch certain messages (WM_QUERYENDSESSION, WM_ENDSESSION). See Logging Off (Windows) on MSDN.
3,433,956
3,434,108
C++ / Qt : passing variables to be changed in the class
So I have two forms in my project: MainWindow and Options Form (OptForm; QWidget); Now, I create (simply dragging to a form) a QPushButton in MainWindow to open OptForm, and passing in variables, which OptForm can change. void MainWindow::openOpt() //Slot; QPushButton calls(?) it { OptForm w (this->variable1,this->...
Right now your Widget is destroyed after being created (show() doesn't block and your widget is created on the stack , that's why you don't see anything. If you want to block until the window is closed and then process the result, you could use QDialog and call QDialog::exec(): OptDialog w (this->variable1,this->variab...
3,434,065
3,434,084
Which location address in a pointer refers to
What does the address in a pointer refer to, real address location in main memory or virtual address. Can it be configured. And if it refers to virtual address , does Memory manager needs to convert this address to real address everytime it is accessed
This depends on your system and OS. For a typical windows/linux user space application, the address is a virtual memory address. User space applications have no way of accessing the memory using physical addresses - that's one of the abstractions the OS gives each process. The MMU(Memory management unit) does this tr...
3,434,240
3,434,251
How can I return a value from a class object?
Is it possible to have a class object return a true/false value, so I can do something like this: MyClass a; ... if (a) do_something(); I can accomplish (almost) what I want by overloading the ! operator: class MyClass { ... bool operator!() const { return !some_condition; }; ... } main() MyClass ...
Overload the void * cast operator: operator void * () const { return some_condition; }; this is how streams work, allowing you to say: if ( cin ) { // stream is OK } The use of void * rather than bool prevents the cast being used by mistake in some contexts, such as arithmetic, where it would not be desirable. Unl...
3,434,256
3,434,315
Use the auto keyword in C++ STL
I have seen code which use vector, vector<int>s; s.push_back(11); s.push_back(22); s.push_back(33); s.push_back(55); for (vector<int>::iterator it = s.begin(); it!=s.end(); it++) { cout << *it << endl; } It is same as for (auto it = s.begin(); it != s.end(); it++) { cout << *it << endl; } How safe is in this ...
The auto keyword is simply asking the compiler to deduce the type of the variable from the initialization. Even a pre-C++0x compiler knows what the type of an (initialization) expression is, and more often than not, you can see that type in error messages. #include <vector> #include <iostream> using namespace std; int...
3,434,534
3,434,558
How do I code and pass a (reference to a std::vector)?
I can't seem to get this right. class Tree { Node* root; vector& dict; } class Node { vector& dict; char* cargo; Node left; Node right; } I want each instance of Tree to have it's own dict, and I want it to pass a reference to the dict to the node constructor, which would recursivel...
You haven't specified what you've tried that isn't working, but I suspect you are having trouble in the constructors because a reference can't be assigned to; you have to initialize it. Also, when you use std::vector, you have to use a template parameter for the element type. So you can't just use vector&, you need ve...
3,434,582
3,434,623
simplify simple C++ code -- something like Pythons any
Right now, I have this code: bool isAnyTrue() { for(std::list< boost::shared_ptr<Foo> >::iterator i = mylist.begin(); i != mylist.end(); ++i) { if( (*i)->isTrue() ) return true; } return false; } I have used Boost here and then but I couldn't really remember any simple way to write it ...
C++ does not (yet) have a foreach construct. You have to write that yourself/ That said, you can use the std::find_if algorithm here: bool isAnyTrue() { return std::find_if(mylist.begin(), mylist.end(), std::mem_fun(&Foo::isTrue)) != mylist.end(); } Also, you should probably be using std::vector or std:...
3,434,699
3,438,649
boost gzip reading files with trailing garbage
I'm using boost::iostreams::gzip_decompressor with boost::iostreams::filterimg_streambuf to read gzip files. some of my files have what zcat calls trailing trash % zcat somefile data data data gzip: somefile: decompression OK, trailing garbage ignored What I want is for boost gzip to behave the same way. When trying ...
Ok, What finally worked for me is to use zlib with different window_bits so it can decompress gzip. #include <zlib.h> # for MAX_WBITS static int read_gzip(fs::path f, stringstream& s) { ifstream file(f.string().c_str(), ios_base::in | ios_base::binary); io::filtering_streambuf<io::input> in; ...
3,434,803
3,434,866
Returning From a Void Function in C++
Consider the following snippet: void Foo() { // ... } void Bar() { return Foo(); } What is a legitimate reason to use the above in C++ as opposed to the more common approach: void Foo() { // ... } void Bar() { Foo(); // no more expressions -- i.e., implicit return here }
Probably no use in your example, but there are some situations where it's difficult to deal with void in template code, and I expect this rule helps with that sometimes. Very contrived example: #include <iostream> template <typename T> T retval() { return T(); } template <> void retval() { return; } template...
3,434,954
3,434,988
Some things missing from gnu gcc compiler headers? (commctrl.h)
I have been using the gcc compiler with code::blocks ide, and have noticed there are some things missing in the commctrl.h which are: PBS_MARQUEE and PBM_SETMARQUEE to set a progress bar to marquee animation style. LVS_EX_DOUBLEBUFFER for a double buffer on a list view... there are probably a lot more missing, but thes...
GCC does not do a good job of supporting Windows. This is a prime example of why. It's an excellent compiler. and on Unix boxes there's nothing else I'd ever use, because it's an excellent compiler, but... MinGW simply does not include a few of the Windows headers, and for those that they do, they aren't always as up t...
3,435,002
3,435,080
Writing binary files C++, way to force something to be at byte 18?
I'm currently trying to write a .bmp file in C++ and for the most part it works, there is however, just one issue. When I start trying to save images with different widths and heights everything goes askew and I'm struggling to solve it, so is there any way to force something to write to a specific byte (adding padding...
There are several sort of obvious answers, such as keeping your data in memory in a buffer, then putting the desired value in as bufr[offset]=mydata;. I presume you want something a little fancier than that, because you are, for example, doing this in a streaming sort of application where you can't have the whole obje...
3,435,026
3,435,076
Can const-correctness improve performance?
I have read numerous times that enforcing const-correctness in your C or C++ code is not only a good practice with regards to maintainability, but also it may allow your compiler to perform optimizations. However, I have read the complete opposite, too — that it does not affect performance at all. Therefore, do you hav...
const correctness can't improve performance because const_cast and mutable are in the language, and allow code to conformingly break the rules. This gets even worse in C++11, where your const data may e.g. be a pointer to a std::atomic, meaning the compiler has to respect changes made by other threads. That said, it is...
3,435,225
3,486,307
C++ meta-programming doxygen documentation
I am documenting some code which uses meta-programming heavily, for example: template<rysq::type A, rysq::type B, rysq::type C, rysq::type D, class Transform> struct Kernel<meta::braket<A,B,C,D>, Transform, typename boost::enable_if< quadrature<meta::braket<A,B,C,D>, Transform> >::ty...
Use preprocessor macros. Here's an example from the not-yet-official Boost.XInt library (presently queued for review for inclusion in Boost): #ifdef BOOST_XINT_DOXYGEN_IGNORE // The documentation should see a simplified version of the template // parameters. #define BOOST_XINT_INITIAL_APARAMS ... #defin...
3,435,333
3,435,384
Is it possible to accept from the user (standard input) to the string stream directly?
Here is a sample program that uses stringstream. The goal is to accept lines from the user(standard input) and print each word in a separate line. int main() { std::istringstream currentline; std::string eachword; std::string line; // Accept line from the standard input till EOF is reached while (...
std::getline needs a string reference argument, and that's where it places the line it has obtained, so of course you can't avoid passing such an argument (and still use that function). You could elegantly encapsulate the construct, if you need it often -- e.g.: bool getline(std::istream& i, std::istringstream& curren...
3,435,586
3,435,626
Function C++ to C# (safe code)
c++: static void doIp(byte data[]) { unsigned char j, k; byte val; byte buf[8]; byte *p; byte i = 8; for(i=0; i<8; i++) { val = data[i]; p = &buf[3]; j = 4; do { for(k=0; k<=4; k+=4) { p[k] >>= 1; if(val & 1) p[k] |= 0x80; val >>= 1; } ...
class someclass { public static void doIp(byte[] data) { uint j, k; // these are just counters, so uint is fine byte val; byte[] buf = new byte[8]; // syntax changed here byte p; // you end up using p simply as an offset from buf byte i = 8; f...
3,435,595
3,435,611
How to eliminate all sources of randomness so that program always gives identical answers?
I have C++ code that relies heavily on sampling (using rand()), but I want it to be reproducible. So in the beginning, I initialize srand() with a random seed and print that seed out. I want others to be able to run the same code again but initializing srand() with that same seed and get exactly the same answer as I di...
The solution is to use the same code in all cases - the Boost random number library is infinitely better than any C++ standard library implementation, and you can use the same code on all platforms. Take a look at this question for example of its use and links to the library docs.
3,435,601
3,435,620
Adding static member variable to third-party class
I'm using Boost.Property_Tree for a project and I want to add a small bit of functionality to it. I want to add a "fromFile" static member variable that will figure out the file type and then use the proper parser. In my project, this is currently how I've got it. typedef boost::property_tree::ptree ConfigNode; Then I...
Nope. There's no clean way to do this. You have two options: Declare your functions and variables outside of the class completely (e.g. in another class or global in some namespace). Subclass boost::property_tree, adding your static member(s).
3,435,723
3,435,740
How can I use an initialization list to select which constructor to use?
I just asked this question and the good answers mentioned using an initialization list. So I looked it up in many various places. It was often said that one can use an initialization list to select which constructor to use. class First {private: int a, b, c; public: First(int x); First(int x, int y); } ...
I'm not quite sure I follow. As it stands, by providing an argument to x and y (and therefore z), both constructors will be available to call, resulting in ambiguity. I think what you're looking for is: class First { public: First(int x); First(int x, int y, int z = 0); }; // invoked as First f(1); First::Firs...
3,435,730
3,435,753
Edit Control Text Changed Message in C++\Win32
What is the Message that matches the TextChanged property in .NET for C++\Win32?
Assuming you're talking about the Edit control, EN_CHANGE is the notification you're looking for. The parent of the Edit control receives the notification via the WM_COMMAND message, with HIWORD(wParam) == EN_CHANGE, LOWORD(wParam) == edit control identifier and lParam == edit control HWND.
3,435,738
3,435,759
What is considered a small object in C++?
I've read about Small-Object Allocation in "Modern C++ Design". Andrei Alexandrescu argues that the general purpose operators (new and delete) perform badly for allocating small objects. In my program there are lot of objects created and destroyed on the free store. These objects measure more than 8000 bytes. What size...
The definition of "small" varies, but generally speaking, an object can be considered "small" if its size is smaller than the size overhead caused by heap allocation (or is at least close to that size). So, a 16 byte object would probably be considered "small" in most cases. A 32 byte object might be considered small ...
3,435,976
3,435,983
Why do people use some thing like char*&buf?
I am reading a post on Stack Overflow and I saw this function: advance_buf( const char*& buf, const char* removed_chars, int size ); What does char*& buf mean here and why do people use it?
It means buf is a reference to a pointer, so its value can be changed (as well as the value of the area it's pointing to). I'm rather stale in C, but AFAIK there are no references in C and this code is C++ (note the question was originally tagged c). For example: void advance(char*& p, int i) { p += i; // ...
3,436,015
3,436,035
c++ Start process with argument
i know how to Start process with argument but im trying to create a program that uses this arguments. for example IE8 uses Process::Start( "IExplore.exe","google.com"); as a argument to open new window with url google.com. i want my program to use the argument are send it but i don't know how to get the the argument. l...
Assuming you write your entry point something like this: int main(int argc, char* argv[]) Then argc is the number of arguments used to invoke your program and argv are the actual arguments. Try it out: #include <cstdio> int main(int argc, char* argv[]) { for (int i = 0; i < argc; ++i) printf("%s\n", argv[...
3,436,063
3,436,077
Which method to use to check if array key exists in std::map?
I'm using the following code in some cases: #define array_key_exists(find_key, arr) (arr.find(find_key) != arr.end()) But i also use simply this method: if(SomeMap["something"]){ // key exists } I am using String to int map. Are they both as fast...? Or is there a possibility for errors with the second case, assu...
The second if-statement will always be entered, because if the key doesn't exist it will be created. (After which, subsequent calls will just return the existing element.) If you want to find a value and use it if it exists, you typically do this: std::map<T>::iterator iter = theMap.find(theKey); if (iter != theMap.end...
3,436,099
3,436,114
Give up root privilegies?
I have a program which runs a bunch of tasks as root at launch. After that it needs to drop to a different user. How can that be done? And just wondering, is it possible to reacquire root without relaunching the program?
The short answer is to use the setuid() function. It is not possible to reacquire root privileges after switching to a non-root user.
3,436,229
3,436,317
Problem with clear() in custom vector STL container
Following an example in Accelerated C++, I created a custom STL container, which is a simplified version of std::vector, called Vec. Everything worked fine, until, emboldened by success, I tried to add a Vec::clear() that will clear the vector. Here's the latest class definition (only the relevant parts to this questi...
You're losing (and therefore leaking) data by setting it to 0. When you clear, you're only taking away the available (allocated) elements, the buffer (data) stays. You should replace data = avail = 0; with avail = data;.
3,436,340
3,436,512
Use of Boost Bimap in C++
C++ Boost has Bimap container that is a bidirectional map: http://www.boost.org/doc/libs/1_43_0/libs/bimap/doc/html/index.html Does anyone know the performance of Boost::bimap? I mean what's the time complexity of accessing an element in the map? Is it as quick as unordered_map access (which is O(1))? Thanks!
AFAIK each different container of this library have different operation complexity relative to the implementation (like for the stl containers). For details necessary to make your choice, read : http://www.boost.org/doc/libs/1_43_0/libs/bimap/doc/html/boost_bimap/the_tutorial/controlling_collection_types.html
3,436,356
3,436,375
C++ - What would be faster: multiplying or adding?
I have some code that is going to be run thousands of times, and was wondering what was faster. array is a 30 value short array which always holds 0, 1 or 2. result = (array[29] * 68630377364883.0) + (array[28] * 22876792454961.0) + (array[27] * 7625597484987.0) + (array[26] * 2541865828329.0) ...
That is a ridiculously premature "optimization". Chances are you'll be hurting performance because you are adding branches to the code. Mispredicted branches are very costly. And it also renders the code harder to read. Multiplication in modern processors is a lot faster than it used to be, it can be done a few clock ...
3,436,518
3,436,529
c++ function template compiles error "‘containerType’ is not a template"
I'm trying to write a function to "stringify" parameters for logging purpose. For example, I'd like to write something like this: vector<string> queries; set<uint_8> filters; LOG(INFO) << stringify<vector, string>(queries); LOG(INFO) << stringify<set, uint_8>(filters); Here is the function template I wrote: template ...
You need to use a template template parameter, e.g., template <template <typename> class containerType, typename elemType> string _stringify(const string name, const containerType<elemType>& elems) Note that if you are expecting to use this with standard library containers, most of them have several template parameter...
3,436,569
3,436,594
How do I set X coordinate of button without changing: y, width, height
I know I can use MoveWindow to move it but I only want to move the button on the x axis. Thanks.
I figured it out. You can get the button's (screen) position using GetWindowRect, then you can use ScreenToClient to get it's location in the form. Example: RECT buttonScreenRect; GetWindowRect(hwnd, &buttonScreenRect); POINT buttonClientPoint; buttonClientPoint.x = buttonScreenRect.left; buttonClientPoint.y = buttonS...
3,436,605
3,436,614
C++ memory management for a vector with variable length items
Take a variable length struct (if this were a real program, an int array would be better): #include <vector> struct list_of_numbers(){ int length; int *numbers; //length elements. }; typedef std::vector<list_of_numbers> list_nums; //just a writing shortcut (...) And build a vector out of it: list_nums lst(10); //...
In general, you would want to put cleanup code in the destructor of the object (~list_of_numbers()) and memory creating code in the constructor (list_of_numbers()). That way these things are handled for you when the destructor is called (or when the object is created).
3,436,618
3,436,732
Is it good style to hide shared_ptr behind a typedef?
I'd like to reduce some visual noise in the code and hide shared_ptr behind a typedef like this: typedef boost::shared_ptr<SomeLongClass> SomeLongClassPtr; So this: void foo(const boost::shared_ptr<SomeLongClass>& a, boost::shared_ptr<SomeLongClass>& b); becomes this: void foo(const SomeLongClassPtr& a, Some...
Given that std::string is itself a typedef, I think you are fine. I do it myself. Even Scott Meyers recommends typedef for ease of reading code in cases like yours. EDIT: Effective C++, Second Edition, Page 120, Item 28, fourth paragraph. "...provide typedefs that remove the need..." More Effective C++, 7th printing,...
3,436,749
3,436,763
Reconstituting numbers in C/C++
I have a stream of bytes that is being read in from a socket (little endian). Can someone tell me why only the last one of the methods below gives the correct answer? I suspect it's to do with the carry bit but not sure. I've always found that when printing binary data in hex form. e.g. printf("%02X", data); it som...
When signed datatypes are being cast into higher datatypes, the most significant bit is used as a sign bit. You should have unsigned char in your union. In your case 500 = 256 + 244 = 0x1f4 and the byte 244 has the most significant bit set, so when promoted becomes 0xfffffff4.
3,436,762
3,959,244
Collada loading with libxml2
I want to load collada with libxml2. I get the COLLOADA node, okay, then I try to get the children tag - FAIL, the children tag name is "text". Why? How can i get the child of COLLADA node? xmlNode* geometries = xmlDocGetRootElement(doc)->children; //at THIS point the geometries->name == "text" WHY? //IS not it supp...
Take a look at this method from this example in the libxml2 website: static void print_element_names(xmlNode * a_node) { xmlNode *cur_node = NULL; for (cur_node = a_node; cur_node; cur_node = cur_node->next) { if (cur_node->type == XML_ELEMENT_NODE) { printf("node type: Element, name: %s\n"...
3,436,789
3,437,140
How to remove a VS command line switch
When I set additional compiler options for a project in Visual Studio 2008, they propagate to all files. If I then set additional options for a specific file, they are added to the project's command line and additional options. How can I compile an individual file without the project-wide options?
It looks like your problem is that there's no way to negate /callcap for the one source file where you don't want it. Ugly as it is, you could always place that one source file into a separate static library.
3,436,856
3,436,894
Avoiding Denial of Service attack
when I use recv from windows sockets does using recv can lead to denial of service attack ? If it waits for data forever? So what is the best way for solving this (alarms ?) Thanks & Regards, Mousey.
You seem to mis-understand what denial of service means. An example would be a large number of HTTP requests to a single web-server arriving at such a rate that the web-server software becomes so busy it cannot accept new TCP connections. Wikipedia has a decent article on DoS, read it. recv(2) is just an API. Misuse of...
3,436,857
3,436,862
c++ process start problem with path
I'm using process::start(PATH); to open up the process. The problem is, sometimes it finds the file and sometimes it doesn't. For example, this works: process::start("C:\text.exe"); But this doesn't work: process::start("C:\New Folder\text.exe"); Any idea what the difference is?
You have to escape the \ characters. In a C string \t is the TAB character. Use: process::start("C:\\New Folder\\text.exe");
3,436,887
3,562,526
How to generate dynamic audio signal
I am looking to control some electronic servo's using the headphone port as a the control signal. I need to be able to generate a pulse width modulation signal and change the width of the pulse on the fly rapidly. I would prefer to do this in C# but can c++ is also an option. Any idea's how to go about doing this?
NAudio: http://naudio.codeplex.com/
3,436,922
3,436,941
evaluate whether a number is integer power of 4
The following function is claimed to evaluate whether a number is integer power of 4. I do not quite understand how it works? bool fn(unsigned int x) { if ( x == 0 ) return false; if ( x & (x - 1) ) return false; return x & 0x55555555; }
The first condition rules out 0, which is obviously not a power of 4 but would incorrectly pass the following two tests. (EDIT: No, it wouldn't, as pointed out. The first test is redundant.) The next one is a nice trick: It returns true if and only if the number is a power of 2. A power of two is characterized by havin...
3,436,982
3,437,086
how to create an utf8 string in Google V8 engine
Hello Im using v8 engine embedded in C++ program and I met a string problem. Well of course v8 engine fully support utf8 string, but i just dont know how. char path[ 1024 ]; GetCurrentDirectory( 1024, (LPWSTR)path ); script->Path = String::New(path); However, the result is the only character "D", for String::New on...
Since you had to cast "path" to LPWSTR, it looks like you are calling the wide-string (unicode) Win32 API for GetCurrentDirectory, which is UTF-16. Try declaring "path" as wchar_t instead. If utf_16 is a typedef for wchar_t, it may work directly with String::New.
3,437,017
3,437,037
C++ vectors of classes with constructors
//Using g++ and ubuntu. #include <vector> using namespace std; Define a class: class foo(){ (...) foo(int arg1, double arg2); } Constructor: foo::foo(int arg1, double arg2){ (...) //arrays whose length depend upon arg1 and arg2 } I would like to do something like this: vector<foo> bar(10); //error: no matching fun...
Why are you using new when no dynamic memory needs to be created? Of course using new will fail, it results in a foo* when push_back accepts a foo. (That's what you have a vector of, after all.) What's wrong with push_back? If you want to reserve memory up front, use reserve(); providing a number in the constructor of ...
3,437,110
3,438,004
Why do C and C++ support memberwise assignment of arrays within structs, but not generally?
I understand that memberwise assignment of arrays is not supported, such that the following will not work: int num1[3] = {1,2,3}; int num2[3]; num2 = num1; // "error: invalid array assignment" I just accepted this as fact, figuring that the aim of the language is to provide an open-ended framework, and let the user de...
Here's my take on it: The Development of the C Language offers some insight in the evolution of the array type in C: http://cm.bell-labs.com/cm/cs/who/dmr/chist.html I'll try to outline the array thing: C's forerunners B and BCPL had no distinct array type, a declaration like: auto V[10] (B) or let V = vec 10 (BCPL...
3,437,183
3,437,226
C++ coding standard for small group using modern IDEs
We are going to start a new project in our team which consists of less than 10 developers. We have access to modern IDEs such as VS2010. The project is extremely dynamic (users' needs change very quick) and cross platform. Therefore, I need a highly readable and very detailed C++ coding standard so new developers can e...
Coding standards remain an issue because everyone secretly thinks they can solve all the world's programming problems with a very clever coding standard. And then forcing programmers to follow them. (Pretty much like programming programmers.) Unfortunately, few coding standards address the issues that matter in a com...
3,437,367
3,438,129
RegQueryValueEx and REG_BINARY
I tried to read a REG_BINARY value of the Windows registry, but I don't know how... I'm really new to the c++ world and I hope that you'll be cool and help me with that problem. I found that code on this website, I know this is not doing the job, but just for let you know what I'm trying to do. #include <iostream> #inc...
There are two problems with the code you posted - the buffer for the binary value is too small and KEY_ALL_ACCESS could be too much to ask for, KEY_QUERY_VALUE is enough. Here is the code that has this mistakes corrected. You can change dwReturn[1000] to dwReturn[1] and see that RegQueryValueEx returns an error and t...
3,437,457
3,437,467
Are STL Map or HashMaps thread safe?
Can I use a map or hashmap in a multithreaded program without needing a lock? i.e. are they thread safe? I'm wanting to potentially add and delete from the map at the same time. There seems to be a lot of conflicting information out there. By the way, I'm using the STL library that comes with GCC under Ubuntu 10.04 EDI...
You can safely perform simultaneous read operations, i.e. call const member functions. But you can't do any simultaneous operations if one of then involves writing, i.e. call of non-const member functions should be unique for the container and can't be mixed with any other calls. i.e. you can't change the container fro...
3,437,582
3,437,588
using a string variable declared in one class globally in entire project
I have a string variable as: string name = "MyName"; in one cpp file. How can i use the same string variable in another class within the same project.
extern string name; in the other files, and then link the objects together.
3,438,090
3,438,100
Using boost memory pool in class
I tried to declare a memory pool in my class. But the compiler shows some basic error like missing ')' before ';' or syntax error : 'sizeof' It works well if I used the pool as local variable but I really want to make it live with the class. What's wrong about my usage? Here is the class, the MAX_OBJ is a const class ...
I don't think it as anything to do with boost::pool. But this line: boost::pool m_Pool(sizeof(DWORD) * MAX_OBJ); Should probably be: boost::pool m_Pool; And your constructor should then be: CData::CData() : m_Pool(sizeof(DWORD) * MAX_OBJ) { } You cannot construct members in the class declaration. You can just say:...
3,438,125
3,438,177
non-const pointer argument to a const double pointer parameter
The const modifier in C++ before star means that using this pointer the value pointed at cannot be changed, while the pointer itself can be made to point something else. In the below void justloadme(const int **ptr) { *ptr = new int[5]; } int main() { int *ptr = NULL; justloadme(&ptr); } justloadme funct...
As most times, the compiler is right and intuition wrong. The problem is that if that particular assignment was allowed you could break const-correctness in your program: const int constant = 10; int *modifier = 0; const int ** const_breaker = &modifier; // [*] this is equivalent to your code *const_breaker = & consta...
3,438,132
3,438,211
Serialize and deserialize vector in binary
I am having problems trying to serialise a vector (std::vector) into a binary format and then correctly deserialise it and be able to read the data. This is my first time using a binary format (I was using ASCII but that has become too hard to use now) so I am starting simple with just a vector of ints. Whenever I read...
You can't unserialise a non-POD class by overwriting an existing instance as you seem to be trying to do - you need to give the class a constructor that reads the data from the stream and constructs a new instance of the class with it. In outline, given something like this: class A { A(); A( istream & is );...
3,438,225
3,447,256
equivalent encryption/decryption functions on C++ linux and C# windows
i have both a web gui written in C#, running on IIS server and C++ written engine, running on apache. i need my web gui to encrypt and the C++ engine to decrypt the data. what equivalent function can i use to achieve my purpose ?
You could use MD% since it is built in to the .NET Framework to encript System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] data = System.Text.Encoding.ASCII.GetBytes(Value); data = x.ComputeHash(data); return System.Text.Encoding.ASCII.GetString...
3,438,464
3,438,546
arguments problem help
i have created a win32 window it work fine but im tryin to get command argument using lpcmdline. it works fine but when i try to compare it to string it to does work here is the comparing code TCHAR checking[]=_T("hello"); if(args==checking) // args equals lpcmdline like this LPTSTR args=lpcmdline { TCHAR greeting...
That's not the right way to compare two strings in C++. Given that you're comparing a TCHAR array with an LPTSTR, call _tcscmp instead of using the == operator.
3,438,600
3,438,664
Identify which file has included some particular header file
Sometimes with a complex header structure it happens some header is included, but it is hard to tell where from. Is there some tool (depedency viewer?) or a method how to find the "inclusion stack" (which source / which header / which header / ...) is including one particular header file? If the header file is included...
Someone has posted about it but I can't find this answer. So, In VS, go to your project properties. Choose Configuration Properties / C/C++ / Advanced / Show Includes and set "yes". then compile you cpp file. It looks like this: cpp file: #include <stdio.h> int main() { return 0; } In the output window after comp...
3,438,634
3,439,336
How to get logged-in user's full name in windows?
How to get logged-in user's full name (the one he/she entered as his/her real name) using windows API or something else? For example how to get "John Smith", not "john" (as it were his username). GetUserName(...) doesn't do the job because it returns the username, not the full name.
Did you try GetUserNameEx(NameDisplay,...)?
3,438,884
3,438,902
Class in header file
I'm having a bit of trouble with a C++ program I'm working on. I've created an abstract class with a single pure virtual method. Since the class has no variables or implemented methods, I've stored the class in a header file without an .cpp implementation file (there isn't any need for one). The method is: virtual void...
I think you forgot to put the class qualifier in the .cpp implementation. It should probably read: void Engine::handleEvent() { ... }
3,439,053
3,439,150
Using C++ lambda functions during variable initialisation
I think many of you have this kind of code somewhere: int foo; switch (bar) { case SOMETHING: foo = 5; break; case STHNELSE: foo = 10; break; ... } But this code has some drawbacks: You can easily forget a "break" The foo variable is not const while it should be It's just not beautiful So I started wondering...
This is a fairly common technique in other languages. Almost every high-level feature of Scheme is defined in terms of lambdas that are immediately called. In JavaScript it is the basis of the "module pattern", e.g. var myModule = (function() { // declare variables and functions (which will be "private") retu...
3,439,074
3,439,177
Nested data member pointer - not possible?
The following reduced code sample does not do anything useful but two subsequent assignments to a data member pointer. The first assignment works, the second one gives a compiler error. Presumably because its to a nested member. Question would be: Is it really just not possible to let a member pointer point to a nested...
AFAIK, this is not possible. A pointer-to-member can only be formed by an expression of type &qualified_id, which is not your case. Vite Falcon's solution is probably the most appropriate.
3,439,236
3,439,259
Duplicate Symbol problem
I have a header file MyNameSpace.h where i use namespace as under: namespace NameSpace1 { string first = "First"; ... } namespace NameSpace2 { string top = "Top"; } But when i use the namespace object in my other classes including the header file. I got Duplicate symbol error as NameSpace1::first. What exactly it m...
You shouldn't define globals in headers, you need to tell the compiler it's defined elsewhere with the extern keyword. Otherwise the compiler tries to define the variable in every source file that includes the header. Eg. in MyNameSpace.h you do: namespace NameSpace1 { extern std::string first; } Then you'll do th...
3,439,435
3,514,598
Memory (and other resources) used by individual VirtualAlloc allocation
How much memory or other resources is used for an individual VirtualAlloc (xxxx, yyy, MEM_RESERVE, zzz)? Is there any difference in resource consumption (e.g. kernel paged/nonpaged pool) when I allocated one large block, like this: VirtualAlloc( xxxx, 1024*1024, MEM_RESERVE, PAGE_READWRITE ) or multiple smaller blocks...
Just FYI, you can use GetProcessMemoryInfo and GlobalMemoryStatusEx to get some memory usage measurements. void DisplayMemoryUsageInformation() { HANDLE hProcess = GetCurrentProcess(); PROCESS_MEMORY_COUNTERS pmc; ZeroMemory(&pmc,sizeof(pmc)); GetProcessMemoryInfo(hProcess,&pmc, sizeof(pmc)); std::c...
3,439,560
3,439,676
Can anyone decipher why these two conversions to unsigned long long give different results?
LARGE_INTEGER lpPerformanceCount, lpFrequency; QueryPerformanceCounter(&lpPerformanceCount); QueryPerformanceFrequency(&lpFrequency); (Count.QuadPart is a long long showing a CPU count) (Freq.QuadPart is a long long showing frequency of Count for a second) Attempting to print microseconds in real time. stable output:...
Are you sure %llu prints a reasonable double? lpPerformanceCount.QuadPart / lpFrequency.QuadPart gives you a time, rounded to full seconds. lpPerformanceCount.QuadPart % lpFrequency.QuadPart gives you a tick count (number ticks since last full second). Adding a count to a time gives you.. how to put that politely... ...
3,439,589
3,441,171
how to show text an d icon on button in win 32 c++?
I wanted to get both icon and text, so I didn't set BM_ICON on my button. In WM_INITDIALOG (yes, the button is in a dialog) I say: SendDlgItemMessage(hwndDlg, IDC_CREATE, BM_SETIMAGE, IMAGE_ICON, reinterpret_cast<LPARAM>(create_image)); It doesn't work. The button shows text only. Now, if I do set the BS_ICON style, i...
I believe what you want is called an "OwnerDraw" button. You can mix text and graphics on them. You provide the 3 button-states and it draws what you tell it. Ownerdraw Control Example: http://www.codeguru.com/cpp/controls/buttonctrl/advancedbuttons/article.php/c5161 The link above might be a bit extreme, but you now h...
3,439,594
3,439,672
How to optimize this code?
Profiler says that 50% of total time spends inside this function. How would you optimize it? It converts BMP color scheme to YUV. Thanks! Update: platform is ARMV6 (writing for IPhone) #define Y_FROM_RGB(_r_,_g_,_b_) ( ( 66 * _b_ + 129 * _g_ + 25 * _r_ + 128) >> 8) + 16 #define V_FROM_RGB(_r_,_g_,_b_) ( ( 112 * _b_ -...
Unless I am missing something the follow code seems to be repeated in both loops, so, why not go through this loop once? This may require some changes to your algorithm, but it would improve performance. for (int x = 0; x < half_width; x ++) { int R = source_scan[0]; int G = source_scan[1]; int B = source_sc...
3,439,730
3,439,970
Code Review question - should I allow this passing of an auto_ptr as parameter?
Consider the following example code which I have recently seen in our code base: void ClassA::ExportAnimation(auto_ptr<CAnimation> animation) { ... does something } // calling method: void classB::someMethod() { auto_ptr<CAnimation> animation (new CAnimation(1,2)); ClassA classAInstance; classAInstance.ExportAni...
It all depends on what ExportAnimation is and how it is implemented. Does it only use the object for the duration of the call and then leaves it? Then convert to a reference and pass a real reference. There is no need to pass membership and the argument is not optional, so void ExportAnimation( CAnimation const & ) su...
3,440,034
6,758,593
Cascading specific windows in a MFC MDI application
A MDIParent Wnd has many MDIchild Wnds, and also few child dialogs. Dialogs are created this way --- CAutoDlg *pDlg = new CAutoDlg; pDlg->Create(IDD_AUTOCARD,this); I want to cascade only a specific type of dialogs, say dialogs of CAutoDlg type only. If i give MDICascade() it cascades all the child windows and dial...
There is no direct way to do this. You can have collection of CAutoDlg into some container. Using that container call appropriate function to cascade. You may use the CAutoDlg's constructor to add dialog object into that container, and use destructor to remove dialog reference from container.
3,440,066
3,440,166
Why is it so 'hard' to write a for-loop in C++ with 2 loop variables?
Possible Duplicate: In C++ why can’t I write a for() loop like this: for( int i = 1, double i2 = 0; … A C developer would write this: int myIndex; for (myIndex=0;myIndex<10;++myIndex) ... A C++ developer would write this to prevent the loop variable from leaking outside the loop: for (int myIndex=0;myIndex<10;++myI...
You just have to understand the first statement is a declaration (and that comma is not the comma operator). It's not any harder to do: for (int i, double d; ...) Than it is: int i, double d; Because for (init cond; expr) statement gets expanded to: { init while (cond) { statement expr; ...
3,440,115
3,440,206
HTTP Content-Length incorrect size served?
I'm serving some files locally via HTTP using QTcpSocket. My problem is that only wget downloads the file properly, firefox adds four extra bytes to the end. This is the header I send: HTTP/1.0 200 Ok Content-Length: 382917; Content-Type: application/x-shockwave-flash; Content-Disposition: attachment; filename=...
You should not be terminating the lines with semicolons. At first glance this seems like the most likely problem. I don't know much about QDataStream (or QT in general), however a quick look at the QDataStream documentation mentions operator<<(char const*). If you are passing a null terminated string to QDataStream, yo...
3,440,631
3,440,724
C++\Win32 API - Difference between WC_BUTTON and "BUTTON" window classes
Is there a difference or is it as simple as #define WC_BUTTON "BUTTON"? Also, if I use InitCommonControlsEx in place of InitCommonControls, do I still need to include a manifest?
Yes, its as you say: CommCtrl.h // Button Class Name #define WC_BUTTONA "Button" #define WC_BUTTONW L"Button" You still need a manifest if you use InitCommonControlsEx as you need to use V6 of the common controls.
3,440,693
3,440,746
Simple interactive prompt in C++
I work on an application that usually runs unattended. Now I need to add to it something like an interactive prompt. In the interactive mode the operator will be able to give simple commands to the application - nothing fancy, simple commands like start and stop. Parametrized commands (e.g. repeat 10) and commands hist...
Readline is one the best known libraries for this http://tiswww.case.edu/php/chet/readline/rltop.html It is covered by GPL, so it is only possible to use in GPL-compatible programs. I did a quick search for alternatives, and found this: http://github.com/antirez/linenoise
3,440,729
3,440,845
Premature optimization or am I crazy?
I recently saw a piece of code at comp.lang.c++ moderated returning a reference of a static integer from a function. The code was something like this int& f() { static int x; x++; return x; } int main() { f()+=1; //A f()=f()+1; //B std::cout<<f(); } When I debugged the application using my cool Visual...
This is what The Standard says about += and friends: 5.17-7: The behavior of an expression of the form E1 op= E2 is equivalent to E1 = E1 op E2 except that E1 is evaluated only once.[...] So the compiler is right on that.
3,440,831
3,440,995
Simplest way to automate ticket adding in Trac from C/C++
I developing program and i writing error handler, i want to do in her automate error ticket adding to trac webapge. Anyone know simplest way to do this? Simplest of connecting libcurl to PHP script on server who adding ticket. Maybe some library to do this? Or working code snipet?
from the server you can programatically add tickets using the trac package in python, which is trac's native language. If you want to do in C/C++ I think you can achive it issuing xml-rpc calls if the server has the xml-rpc plugin installed[0]. [0] http://trac-hacks.org/wiki/XmlRpcPlugin
3,441,486
3,441,571
How to deal with NaN's when reading in a csv file in C++
I'm reading in a csv file of time-series data into a C++ program. My data however contains some NaN's. For example: 1-Jul-2010, 1.0 2-Jul-2010, 2.0 3-Jul-2010, NaN 4-Jul-2010, 3.0 To deal with this I wrote a short script in Matlab which replaces all the NaN's with 0.0 - I then read in the new file without t...
As David Given already mentioned, you do not have to pre-process the file at all. strtof() and strtod() are both able to convert the NaN string to the NaN float/double value. If you want to replace the values with 0.0 in your dataset, you can do so using the isnan() function. if (isnan(val)) { val = 0.0; }
3,441,534
3,442,734
OpenGL Nvidia Driver 259.12 texture not working
My OpenGL application which was working fine on ATI card stopped working when I put in an NVIDIA Quadro card. Texture simply don't work at all! I've reduced my program to a single display function which doesn't work: void glutDispCallback() { //ALLOCATE TEXTURE unsigned char * noise = new unsigned char [32 * 32 * 3];...
I found the error. Somewhere else in my code I had initialized a GL_TEXTURE_3D object and had not called glDisable(GL_TEXTURE_3D); Even though I had called glBindTexture(GL_TEXTURE_2D, textureID); it should have bound a 2D texture as the current texture and used that - as this code always worked on ATI cards. Well ap...
3,441,537
3,441,580
API For KMP or Boyer-Moore string pattern matching in C++ / STL?
Wondering, if I want to replace strstr with a better string matching algorithm, like KMP or Boyer Moore, is there one in C++ or do we have to write on our own? Wondering, what is the practical string matching function that everyone uses other than strstr? This is with respect to C++/STL under Unix/Linux platform.
I haven't seen many that use features specific to C++, but there are quite a few implementations of KMP and (especially) variants of Boyer-Moore (e.g., Boyer-Moore-Horspool) around that are easily usable from C++.
3,441,711
3,441,741
Reverse iterating with 2 loops?
Basically I want to reverse iterate through 2 std::vectors. a layer has a vector of shapes. usually I could do something like this: for(int i = 0; i < layers.size(); ++i) { for(int j = 0; j < layers[i].shapes.size(); ++j) { layers[i].shapes[j].dosomething(); } } However right now I need to reverse itera...
The easy way: for(int i = layers.size() - 1; i >= 0; --i) { for(int j = layers[i].shapes.size() - 1; j >= 0; --j) { layers[i].shapes[j].dosomething(); } } The "proper" way: for(vector<Layer>::reverse_iterator i = layers.rbegin(); i != layers.rend(); ++i) { for(vector<Shape>::reverse_iterator j = i->s...
3,441,853
3,442,026
Single Responsibility in C++ - Should I implement it using friend classes or more accessors?
I wish to follow the Single Responsibility principle in C++. However, as I break up classes, it seems that in order for classes to "see" each other, I have the following choices: Add many more accessors for each class Make classes friends of each other Improve the design (maybe the fact that I would have to do 1 or 2...
Now that you have a group of classes that all need to work together, you should consider how they should work together. If it's via accessor functions or friends, then you're tightly coupling the classes. It would be difficult in the future to drop in a new class that does something different. It's also difficult to...
3,441,866
3,443,746
Using unique dynamic variable names (not variable values!)
Ok so, this is more a sanity check than anything else. Lets asume we have a struct called lua_State, now I need to create a uncertain amount of unique lua_State's. To make sure I don't use the same variable name twice I would need to have some sort of way to get an unique variable every time i make a new state. However...
Use a std::vector to both store the created states and generate sequential identifiers (i.e. array indices). Unless I'm missing something, then you are grossly over-complicating your requirements. std::vector<lua_State *> stateList; // create a new Lua state and return it's ID number int newLuaState() { stateList....
3,442,217
3,442,543
Is it possible to programmatically determine which will be faster; using remainder operator or a conditional?
wraparound_counter & operator ++() { m_count = (m_count + 1) % upper_limit; /*if (upper == m_count) m_count = lower; ++m_count;*/ return *this; } It is my understanding that on some systems using the remainder operator trick will be faster, but on others the conditional will be faster. Is there...
For most platforms, you can assume that the conditional will be faster. This is because most modern architecture where branch mispredictions are expensive have some form of conditional move instruction, which the compiler will utilize to perform the requested check & assignment. For example, my gcc translates this: n++...
3,442,227
3,442,261
VB.net faster than C++?
Possible Duplicate: Why does C# execute Math.Sqrt() more slowly than VB.NET? I'm running into an interesting problem, wherein I have code in VB.net and the exact same code in C++. I'd expect C++ to naturally run a tad faster than VB.net, but instead I'm getting the exact opposite: VB.net runs more than twice as fast...
The VB.Net solution computes the square root once at the beginning of the loop, while C++ (and C and C# and Java and so on) all compute the square root every time through the loop because their looping primitives are defined differently.
3,442,423
3,442,445
C++: break the main loop
I am preparing some code: for(int a = 1; a <= 100; a++) //loop a (main loop) { for(int b = 1000; b <= 2000; b++) //loop b { if(b == 1555) break; } for(int c = 2001; c <= 3000; c++) //loop c { . . . } } I want to break the main loop (loop variable ...
I recommend refactoring your code into a function. Then you can just return from that function instead of using break: void myFunc() { for(int a = 1; a <= 100; a++) //loop a (main loop) { for(int b = 1000; b <= 2000; b++) //loop b { if(b == 1555) // Logic is just an example, ...
3,442,520
3,442,561
how copy from one stringstream object to another in C++?
I have std::stringstream object ss1. Now, I would like to create another copy from this one. I try this: std::stringstream ss2 = ss1; or: std::stringstream ss2(ss1) neither works The error message is like this: std::ios::basic_ios(const std::ios &) is not accessible from bsl::basic_stringstream, bsl::allocator>:...
Indeed, streams are non-copyable (though they are movable). Depending on your usage, the following works quite well: #include <iostream> #include <sstream> int main() { std::stringstream ss1; ss1 << "some " << 123 << " stuff" << std::flush; std::stringstream ss2; ss2 << ss1.rdbuf(); // copy everything...
3,442,824
3,442,883
Help with this algorithm
I have an algorithm that can find if a point is inside a polygon. int CGlEngineFunctions::PointInPoly(int npts, float *xp, float *yp, float x, float y) { int i, j, c = 0; for (i = 0, j = npts-1; i < npts; j = i++) { if ((((yp[i] <= y) && (y < yp[j])) || ((yp[j] <= y) && (y < yp[i]))) ...
Beware: this answer is wrong. I have no time to fix it right now, but see the comments. This casts a ray from the point to infinity, and checks for intersections with each of the polygon's edges. Each time an intersection is found, the flag c is toggled: c = !c; So an even number of intersections means an even number ...
3,443,026
3,443,092
Forward Declarations and Includes
When working with a library, whether it be my own or external, there are lot of classes with forward declarations. The same classes also have includes as well depending on the situation. When I use a certain class, I need to know whether certain objects that the class uses, are forward declared or are they #include(d)....
In a source file you should not depend on what the other header files include. You should explicitly include every type that your code depends on. If you do not use a type (ie just passing a pointer or a reference around) then you don't need its definition so don't include its header file (The header file for the met...
3,443,222
3,443,231
C style char arrays - How many bytes do we store?
char firstName[32]; I understand that each char occupies 1 byte in memory. So does the above occupy 32 bytes of memory? Am I missing a pointer that takes up memory too or is this just 32 bytes?
No, that takes up exactly 32 bytes of memory. There is no pointer. This is often an area of confusion, since an array name silently "decays" to a "char*" char* fname = firstName; So, firstName may be of type const char*, but it is not itself a char* variable. It is exactly like: int x = 5; x is int variable and tak...
3,443,270
3,443,363
Is there a safe way to use setjmp() and longjmp() in C++?
I was under the impression that using setjmp() and longjmp() in C++ was almost guaranteed to mess up the stack, since these functions don't perform unwinding like, say, exceptions do. This MSDN page, however, indicates that the Microsoft implementation can be told to invoke the destructors of local objects, which impli...
If you have some really weird requirement that doesn't allow you to control the flow of the program normally, with conditionals/loops/breaks, I would prefer to use an exception over jmp. There are scenarios where using an exception to control flow is acceptable. I think one of Boost.Graph's search functions throws an e...
3,443,303
3,443,337
C++ Techniques For Newbies
Is there any good list of techniques + descriptions for C++ newbies. I was thinking of a list describing RAII, RVO, Lvalues... This would be for newbies that don't currently understand those techniques or come from other languages where those are not applicable. Something short & sweet would be preferred :-)
Yes, they're in two very great books authored by the same person. Effective C++ More Effective C++