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,436,115
2,437,760
Drag and Drop text - What am I missing?
I am trying to add drag-and-drop text to my Doc-View App. I added the COleDropTarget variable to the view class, registered it in OnCreate(). I added OnDragEnter(), OnDragOver(), OnDragLeave() and OnDrop() to that class as virtual overrides, but none of them are ever called. I previously had added m_pMainWnd->DragAccep...
Solved: In using F1 to get the syntax for OnDrop and the others, MSDN gave me: virtual BOOL OnDrop( CWnd* pWnd, COleDataObject* pDataObject, DROPEFFECT dropEffect, CPoint point ); But the correct virtual function does not have the first parameter and should be: virtual BOOL OnDrop( COleDataObject* pDat...
2,436,125
2,436,147
C++ Access derived class member from base class pointer
If I allocate an object of a class Derived (with a base class of Base), and store a pointer to that object in a variable that points to the base class, how can I access the members of the Derived class? Here's an example: class Base { public: int base_int; }; class Derived : public Base { public: int d...
No, you cannot access derived_int because derived_int is part of Derived, while basepointer is a pointer to Base. You can do it the other way round though: Derived* derivedpointer = new Derived; derivedpointer->base_int; // You can access this just fine Derived classes inherit the members of the base class, not the ot...
2,436,165
2,436,351
Emulating Dynamic Dispatch in C++ based on Template Parameters
This is heavily simplified for the sake of the question. Say I have a hierarchy: struct Base { virtual int precision() const = 0; }; template<int Precision> struct Derived : public Base { typedef Traits<Precision>::Type Type; Derived(Type data) : value(data) {} virtual int precision() const { return ...
You can't have function() delegate to templated code directly without selecting between a massive list of all possible types, because templates are expanded at compile-time, and at compile-time function() does not know what derived types it will actually be called with. You need to have compiled instantiations of the ...
2,436,217
2,467,014
Convert image buffer to pdf with ImageMagick in C++
I've downloaded the dll's for ImageMagick and am wondering if anybody knows of some example code to accomplish a simple task: I have generated an image in C++ and have the buffer in RGB format. I need to convert it to PDF format (without writing to a file) before sending it over a TCP socket. Is this doable with ImageM...
Assuming you're using Magick++ Magick::Image has a constructor that can create an image from an in-memory blob and a write() method that can write a PDF (and a bunch of other formats) to an in-memoy blob as well. Note that on my Linux machine ImageMagick appears to be creating a few temporary files during operation. I'...
2,436,283
2,436,344
Displaying text in correct column
After getting a helpful answer here, I have run into yet another problem: displaying two or more strings in the column I want it to be displayed in. For an example of the problem I have, I want this output: Come here! where? not here! but instead get Come here! where? not here! when I ...
As stated, setw() only applies to the next input, and you are trying to apply it to two inputs. An alternative to the other suggestions which gives you a chance to use variables in place of literal constants: #include <iostream> #include <sstream> #include <iomanip> using namespace std; int main() { stringstream s...
2,436,499
2,436,528
Instantiating class with custom allocator in shared memory
I'm pulling my hair due to the following problem: I am following the example given in boost.interprocess documentation to instantiate a fixed-size ring buffer buffer class that I wrote in shared memory. The skeleton constructor for my class is: template<typename ItemType, class Allocator > SharedMemoryBuffer<ItemType, ...
My first question: Does this sort of allocation guarantee that the buffer nodes are allocated in contiguous memory locations, i.e. when I try to access the n'th node from address m_start_ptr + n*sizeof(BufferNode) in my Read() method would it work? No. The reason being that you have the first node only. A...
2,436,564
2,436,617
A rocket following the tracks height. Not Homing Missile
What I am trying to create is a rocket that will hug the track in a straight direction. ie) The rocket travels in a straight direction and can orientate based on its local x axis. This is so it can go up/down ramps and never hit the ground. Currently I am using PhysX opengl and C++. This is the method I'm trying right ...
If your ray trace can determine the height of the terrain at some point out ahead, why couldn't you just determine the height of the terrain at the current horizontal coordinates of the rocket, and render the rocket at a fixed height above that? I.e., you seem to be trying to invent a guidance system for the rocket, wh...
2,436,705
2,436,728
Defining < for STL sort algorithm - operator overload, functor or standalone function?
I have a stl::list containing Widget class objects. They need to be sorted according to two members in the Widget class. For the sorting to work, a less-than comparator comparing two Widget objects must be defined. There seems to be a myriad of ways to do it. From what I can gather, one can either: a. Define a comparis...
If you are only comparing two Widgets to each other, use a member operator <. If you are comparing Widget to something else, define a global operator < (the two parameter version, optionally a friend of the Widget class but that is a separate issue. Functor you really only want if you are doing something a little less...
2,436,755
2,437,076
Compiling a C program with a specific architecture
I was recently fighting some problems trying to compile an open source library on my Mac that depended on another library and got some errors about incompatible library architectures. Can somebody explain the concept behind compiling a C program for a specific architecture? I have seen the -arch compiler flag before an...
Can somebody explain the concept behind compiling a C program for a specific architecture? Yes. The idea is to translate C to a sequence of native machine instructions, which have the program coded into binary form. The meaning of "architecture" here is "instruction-set architecture", which is how the instructions ...
2,436,762
2,443,188
Why are string and vector distinct types?
They're both resizable arrays, and std::basic_string doesn't have any specifically character-related functions like upper(). What's special about string to make it better for character data?
Most of the reason has to do with localization and internationalization (L10I18),performance and for historical reasons. For the L10I18 issues, char_traits was added, and you will note that streams has these as well. The intent was to make "smarter characters" in a way, but the outcome was useless. About the only thin...
2,436,774
2,436,862
Locate modules by stack address
I have a Winodws Mobile 6.1 application running on an ARMV4I processor. Given a stack address (from unwinding an exception), I like to determine what module owns that address. Using the ToolHelpAPI, I'm able to determine most modules using the following method: HANDLE snapshot = ::CreateToolhelp32Snapshot( TH32CS_SNAPM...
The CPU stack contains more than just addresses of code. Function arguments get passed on the stack as well. Only a debugger would know exactly what's in the stack frame, it gets it from the .pdb file. That won't really help you, a program cannot debug itself. On regular Windows, you'd use a minidump to do postmort...
2,436,908
2,436,917
Do I specify exception types in just the function header or declarations as well? (C++)
SVector.H: void pop_back() throw (underflow_error); In my SVector.cpp file, should I also include the throw (underflow_error) part as well? void pop_back() throw (underflow_error) { // implementation } OR void pop_back() { // implementation } Thanks.
15.4/2: If any declaration of a function has an exception-specification, all declarations, including the definition and an explicit specialization, of that function shall have an exception-specification with the same set of type-ids.
2,437,126
2,437,140
How to you find out what group the current user belongs to via c++?
Using my c++ program how can I find out what group the current user running my program belongs to? So my program need to figure out a couple of things : The current username of the user The group the user belongs to How can do the above 2 using c++ on a RedHat / Linux machine?
With getuid(2) and getgid(2). See credentials(7) for more information. Use getpwuid(3) and getgrgid(3) for the names.
2,437,189
2,437,194
Is cin a proper file object?
As in, can I pass cin to any function that accepts an ifstream object?
std::cin is not a file stream, but an input stream, or istream. You can pass it to any function that accepts an istream.
2,437,265
2,438,891
How to pass parameters to manage_shared_memory.construct() in Boost.Interprocess
I've stared at the Boost.Interprocess documentation for hours but still haven't been able to figure this out. In the doc, they have an example of creating a vector in shared memory like so: //Define an STL compatible allocator of ints that allocates from the managed_shared_memory. //This allocator will allow placing co...
I asked the same question on the boost users mailing list and Steven Watanabe replied that the problem was simple: std::vector does not have a constructor of the type (size, allocator). Looking at its documentation I see that the constructor is vector ( size_type n, const T& value= T(), const Allocator& = Allocator() ...
2,437,270
2,438,003
assign member based on string value
I need start off with code because I am not sure what terminology to use. Lets say I have the following code: class Node { public: void Parse(rapidxml::xml_node<> *node) { for (rapidxml::xml_attribute<> *attr = node->first_attribute(); attr; attr = attr->next_attribute()) { std::strin...
For the implementation with a map, you could use pointers-to-members. Then you won't need a deep copy of the map (when you copy it, the pointers in the map still point into the original Node), and it will also allow you to make the whole thing static (this map is unnecessary at per-instance basis). For example: class N...
2,437,283
2,437,336
C/C++ packing signed char into int
I have need to pack four signed bytes into 32-bit integral type. this is what I came up to: int32_t byte(int8_t c) { return (unsigned char)c; } int pack(char c0, char c1, ...) { return byte(c0) | byte(c1) << 8 | ...; } is this a good solution? Is it portable (not in communication sense)? is there a ready-made solut...
I liked Joey Adam's answer except for the fact that it is written with macros (which cause a real pain in many situations) and the compiler will not give you a warning if 'char' isn't 1 byte wide. This is my solution (based off Joey's). inline uint32_t PACK(uint8_t c0, uint8_t c1, uint8_t c2, uint8_t c3) { return (...
2,437,583
2,440,172
A specific string format with a number and character together represeting a certain item
I have a string which looks like this "a 3e,6s,1d,3g,22r,7c 3g,5r,9c 19.3", how do I go through it and extract the integers and assign them to its corresponding letter variable?. (i have integer variables d,r,e,g,s and c). The first letter in the string represents a function, "3e,6s,1d,3g,22r,7c" and "3g,5r,9c" are two...
The description of the string format is not really clear but I think I can answer your question anyway (extracting the integers with the letters and adding(?) them to the proper int variable). So beginning with this string: char* was = "3e,6s,1d,3g,22r,7c"; // was == weird ass string it is probably easiest to tokeni...
2,437,586
2,437,680
Accessing base class's method with derived class's object which has a method of same name
when accessing foo() of "base" using derived class's object. #include <iostream> class base { public: void foo() { std::cout<<"\nHello from foo\n"; } }; class derived : public base { public: void foo(int k) { std::cout<<"\nHello from foo with value = "<<k<<"\n"; ...
You could add using base::foo to your derived class: class derived : public base { public: using base::foo; void foo(int k) { std::cout<<"\nHello from foo with value = "<<k<<"\n"; } }; Edit: The answer for this question explains why your base::foo() isn't directly usable from derived withou...
2,437,763
2,825,320
Testing approach for multi-threaded software
I have a piece of mature geospatial software that has recently had areas rewritten to take better advantage of the multiple processors available in modern PCs. Specifically, display, GUI, spatial searching, and main processing have all been hived off to seperate threads. The software has a pretty sizeable GUI automat...
Firstly, many thanks for the responses. For the responses posted across different forumes see; http://www.sqaforums.com/showflat.php?Cat=0&Number=617621&an=0&page=0#Post617621 Testing approach for multi-threaded software http://www.softwaretestingclub.com/forum/topics/testing-approach-for?xg_source=activity and the fo...
2,437,783
2,438,127
Turning one file with lots of classes to many files with one class per file
How do I turn one file with lots of classes to many files with one class per file? (C\C++) So I have that file with such structure: Some includes and then lots of classes that sometimes call each other: #include <wchar.h> #include <stdlib.h> //... class PG_1 { //... } class PG_2 { //... } //...... class PG_N { //...
Two basic coding style patterns are possible: Class declarations in headers, member function/static data instantiation in .cpp files. Class definitions with in-line implementation in headers Option 2 may lead to code bloat since if you use the class in multiple compilation units you may get multiple copies of the imp...
2,437,858
3,350,263
How to convert AS3 ByteArray into wchar_t const* filename? (Adobe Alchemy)
How to convert AS3 ByteArray into wchar_t const* filename? So in my C code I have a function waiting for a file with void fun (wchar_t const* filename) how to send to that function my ByteArray? (Or, how should I re-write my function?)
A four month old question. Better late than never? To convert a ByteArray to a String in AS3, there are two ways depending on how the String was stored. Firstly, if you use writeUTF it will write an unsigned short representing the String's length first, then write out the string data. The string is easiest to recove...
2,437,914
2,451,818
LLVM JIT segfaults. What am I doing wrong?
It is probably something basic because I am just starting to learn LLVM.. The following creates a factorial function and tries to git and execute it (I know the generated func is correct because I was able to static compile and execute it). But I get segmentation fault upon execution of the function (in EE->runFunctio...
I would bet that the ExecutionEngine pointer is null.... You are missing a call to InitializeNativeTarget, the documentation says: InitializeNativeTarget - The main program should call this function to initialize the native target corresponding to the host. This is useful for JIT applications to ensure that the target...
2,437,918
2,437,994
Windows API - Beginner help
I try to create a very simple app using windows API. I've done some small apps in console. This is the first time I do with Win32 apps. I've searched and found a document from forgers which is recommended in this site. But I try to write very first line: #include <stdafx.h> #include <windows.h> int WINAPI WinMain(...
There are two versions of most windows API calls, one which takes single byte string and one which takes 2 byte unicode strings. The single byte one has an A on the end of the name and the 2 byte one has a W. There are macros defined in windows.h so that if you leave the letter out it picks one or the other depending o...
2,437,937
2,437,945
Mixing c++ standard strings and windows API
Many windows APIs take a pointer to a buffer and a size element but the result needs to go into a c++ string. (I'm using windows unicode here so they are wstrings) Here is an example :- #include <iostream> #include <string> #include <vector> #include <windows.h> using namespace std; // This is the method I'm interest...
In this case, I don't see what std::vector brings to the party. MAX_COMPUTERNAME_LENGTH is not likely to be very large, so I would simply use a C-style array as the temporary buffer.
2,438,049
2,438,063
What is the difference between wmain and main?
So I have some class starting with #include <wchar.h> #include <stdlib.h> and there is a wmain function . How is it different from main function i usually use in my C/C++ programs?
"If your code adheres to the Unicode programming model, you can use the wide-character version of main, which is wmain." http://msdn.microsoft.com/en-us/library/aa299386%28VS.60%29.aspx main( int argc, char *argv[ ], char *envp[ ] ) { program-statements } wmain( int argc, wchar_t *argv[ ], wchar_t *envp[ ] ) { program...
2,438,185
2,438,260
Macro to improve callback registration readability
I'm trying to write a macro to make a specific usage of callbacks in C++ easier. All my callbacks are member functions and will take this as first argument and a second one whose type inherits from a common base class. The usual way to go is: register_callback(boost::bind(&my_class::member_function, this, _1)); I'd lo...
Your problem might be that typeof yields my_class&. It appears to work with boost::remove_reference: #include <boost/bind.hpp> #include <boost/type_traits.hpp> #include <iostream> struct X { void foo(int i) { std::cout << i << '\n'; } void bar() {boost::bind(&boost::remove_reference<typeof(*this)>::type::foo, ...
2,438,247
2,438,254
Why am I getting "too many include files : depth = 1024"?
I'm using Visual Studio 2008 Express edition, and keep getting the following error: "Cascadedisplay.h(4) : fatal error C1014: too many include files : depth = 1024. Obviously I'm doing something very wrong with include files, but I just can't see what. Basically, I have an interface class, StackDisplay, from which I wa...
Is #if !defined... legit? I always used #ifndef. Either way, why does your "base" class require the reference to CascadeDisplay? That doesn't seem right. Consider replacing your call to create a new CascadeDisplay with a call to a pure virtual function in StackDisplay that your subclass must implement appropriately....
2,438,291
2,440,290
Programmatically allow write access for a Registry key
I need to programmatically modify the Access Descriptors on a known Registry key during product installation. The way I want it to work is: The installer is run in Administrative mode. A Registry key is created. A function (the one I need) queries the ACL from the key. If this function finds that the group 'Users' alr...
For getting and setting the ACL of the key you need to use RegGetKeySecurity and RegSetKeySecurity. Then you need to iterate through the ACEs, examining any that apply to the "Users" group SID. Then you'll either modify/remove the existing one and/or add a new one. Be advised that working with ACLs in plain old Win3...
2,438,297
2,438,306
Can we use wmain() with Unix compilers or it'll work only on Windows?
Can we use the wmain() function with Unix compilers or it'll work only on/for Windows?
The only standard signatures for main are: int main(void); int main(int argc, char *argv[]); However, a freestanding implementation can provide extensions/allow other signatures. But those are not guranteed to be portable. wmain looks like a Windows/VS thing. There's not much chance this will work on a *nix/GNU GCC.
2,438,334
2,438,384
Are destructors of automatic objects invoked when terminate is called?
What happens when we throw from a destructor? I know that it causes terminate() to be called, and memory is indeed freed and the destructor is called, but, is this before or after throw is called from foo? Perhaps the issue here is that throw is used while the stack is unwinding that is the problem.
Is this before or after throw is called from foo? This is what is happening: foo() is called An object a of type A is created on the stack The next statement throws Now, the dtor for a is called, which throws another exception std::terminate is called -- which is nothing but abandoning the exception handling mechani...
2,438,801
2,438,823
Handler invocation speed: Objective-C vs virtual functions
I heard that calling a handler (delegate, etc.) in Objective-C can be even faster than calling a virtual function in C++. Is it really correct? If so, how can that be? AFAIK, virtual functions are not that slow to call. At least, this is my understanding of what happens when a virtual function is called: Obtain the po...
This is all, of course, implementation-dependent. I don't know if an Obj-C method call can be "faster" than a virtual function call, but it can certainly be in the ballpark-- there's discussion on the mechanism on SO here: Objective C message dispatch mechanism and Mike Ash has more here: http://www.mikeash.com/pyblog/...
2,438,928
2,438,983
Which constructor of std::vector is used in this case
This looks simple but I am confused: The way I create a vector of hundred, say, ints is std::vector<int> *pVect = new std::vector<int>(100); However, looking at std::vector's documentation I see that its constructor is of the form explicit vector ( size_type n, const T& value= T(), const Allocator& = Allocator() ); ...
You are doing it all wrong. Just create it as an automatic object if all you need is a vector in the current scope and time std::vector<int> pVect(100); The constructor has default arguments for the second and third parameters. So it is callable with just an int. If you want to pass an own allocator, you have to pass ...
2,439,254
2,439,442
How to get the call graph of a program with a bit of profiling information
I want to understand how a C++ program that was given to me works, and where it spends the most time. For that I tried to use first gprof and then gprof2dot to get the pictures, but the results are sometimes kind of ugly. How do you usually do this? Can you recommend any better alternatives? P.D. Which are the open so...
You can try KCachegrind. This is a program that visualizes samples acquired by Valgrind tool called Callgrind. KCachegrind may seem to be not actively maintained, but the graphs he produces are very useful.
2,439,283
2,439,294
How can I create Min stl priority_queue?
The default stl priority queue is a Max one (Top function returns the largest element). Say, for simplicity, that it is a priority queue of int values.
Use std::greater as the comparison function: std::priority_queue<int, std::vector<int>, std::greater<int> > my_min_heap;
2,439,402
2,439,436
Why friend overloaded operator is preferred to conversion operator in this case
Hi I have a code like this, I think both the friend overloaded operator and conversion operator have the similar function. However, why does the friend overloaded operator is called in this case? What's the rules? Thanks so much! class A{ double i; public: A(int i):i(i) {} operator double () const { cout<<...
No conversion is necessary for the overloaded operator> to be called. In order for the built-in operator> to be called, one conversion is necessary (the user-defined conversion operator. Overload resolution prefers options with fewer required conversions, so the overloaded operator> is used. Note that if you were to ...
2,439,461
2,439,980
How to provide stl like container with public const iterator and private non-const iterator?
I have a class that includes a std::list and wish to provide public begin() and end() for const_iterator and private begin() and end() for just plain iterator. However, the compiler is seeing the private version and complaining that it is private instead of using the public const version. I understand that C++ will not...
I think your only option is to rename the private methods (if you need them in the first place). In addition I believe you should rename the typedefs: class MyContainer { public: typedef std::list<Object>::const_iterator iterator; typedef iterator const_iterator; const_iterator begin() const; const...
2,439,494
2,439,712
Forcing value to boolean: (bool) makes warning, !! doesnt
I like (bool) way more, but it generates warnings. How do i get rid off the warnings? I have code like: bool something_else = 0; void switcher(int val = -1){ if(val != -1){ something_else = (bool)val; }else{ something_else ^= 1; } } Should i just do it like everyone else and use '!!' or ma...
another way: switch (val) { case -1: something_else = !something_else; break; case 0: something_else = false; break; default: something_else = true; break; }
2,439,536
2,439,635
strategy to allocate/free lots of small objects
I am toying with certain caching algorithm, which is challenging somewhat. Basically, it needs to allocate lots of small objects (double arrays, 1 to 256 elements), with objects accessible through mapped value, map[key] = array. time to initialized array may be quite large, generally more than 10 thousand cpu cycles. ...
Create a slotted allocator: Allocator is created with many pages of memory, each of equal size (512k, 256k, the size should be tuned for your use). The first time an object asks this allocator for memory it allocates a page. Allocating a page consists of removing it from the free list (no search, all pages are the same...
2,439,556
2,439,600
Check if window is losing focus
Which notification message do you receive if any window is losing focus?
WM_KILLFOCUS. In case you care, wParam will be the handle of the window that's receiving the focus.
2,439,643
2,439,662
Linked List exercise, what am I doing wrong?
Hey all. I'm doing a linked list exercise that involves dynamic memory allocation, pointers, classes, and exceptions. Would someone be willing to critique it and tell me what I did wrong and what I should have done better both with regards to style and to those subjects I listed above? /* Linked List exercise */ #...
There's no need for data to be a pointer. Use the ctor-initializer list, it's better for const-correctness and exception safety. None of your constructors need to have any code inside the body. Your linkedList constructor didn't initialize nodeCount. You aren't using your list's tail pointer for anything. It would sa...
2,439,647
2,439,681
computing hash values, integral types versus struct/class
I would like to know if there is a difference in speed between computing hash value (for example std::map key) of primitive integral type, such as int64_t and pod type, for example struct { int16_t v[4]; };. what about int128_t versus struct {int32_t v[4];}? I know this is going to implementation specific, so my quest...
std::map is not a hash table. It is usually implemented as a balanced binary tree. What you want is std::unordered_map* . And for std::unordered_map, C++ only defines the hash value for the internal types and the common ones** such as std::string. You need to implement the hash function for struct { int16_t v[4]; }; y...
2,439,722
2,439,760
Webservice and ORM Framework?
Does anybody know a good web framework that includes an ORM mapper and allows straight forward implementation of web services? I'm looking for a framework written in PHP or C++. I'm looking for the following features (not all of them required, some will do nicely) data definition in one place used by database and web ...
I would recommend using Zend_Framework and replacing Zend_Db with Doctrine as your ORM. You can use Zend_Service to consume webservices and Zend_Rest_Controller to serve a REST API. There are some good screencasts on integrating Doctrine and Zend here. If you have alot of PHP experience, it shouldn't take very long to...
2,439,791
2,439,871
Nested class or not nested class?
I have class A and list of A objects. A has a function f that should be executed every X seconds (for the first instance every 1 second, for the seconds instance every 5 seconds, etc.). I have a scheduler class that is responsible to execute the functions at the correct time. What i thought to do is to create a new cla...
From what you describe, sounds like it could work :-) IMHO class ATime belongs to the scheduler more than to A. It is necessary for the scheduler to do its job, and it is not needed for A. In fact, A (and the rest of the world) need not even know about its existence - so putting it a private nested class of the schedul...
2,440,033
2,440,086
LALR(1) or GLR on Windows - Alternatives to Bison++ / Flex++ that are current?
UPDATE: This question is out of date, but left for informational purposes. Original Question I have been using the same version of bison++ (1.21-8) and flex++ (2.3.8-7) since 2002. I'm not looking for an alternative to LALR(1) or GLR at this time, just looking for the most current options. Is anyone aware of any later ...
You can try Elsa (now it is a part of Oink project). But it is almost dead now. The only attractive feature of it is that there is a complete and robust C and C++ parser is written on top of it. LLVM contains a reasonably modern parsing framework. And there is a C++ parser as well (see clang project). Some Packrat imp...
2,440,411
2,444,325
Setting Connection Parameters via ADO for SQL Server
Is it possible to set a connection parameter on a connection to SQL Server and have that variable persist throughout the life of the connection? The parameter must be usable by subsequent queries. We have some old Access reports that use a handful of VBScript functions in the SQL queries (let's call them GetStartDate a...
Since no one has ventured an answer I'm guessing there isn't an elegant solution, that said: Global cursors persist for the duration of the connection and can be accessed from any SQL or stored proc so you could execute this once on the connection: DECLARE KludgeKursor CURSOR GLOBAL STATIC FOR SELECT StartDate = '2010-...
2,440,420
2,440,430
Compare equality of char[] in C
I have two variables: char charTime[] = "TIME"; char buf[] = "SOMETHINGELSE"; I want to check if these two are equal... using charTime == buf doesn't work. What should I use, and can someone explain why using == doesn't work? Would this action be different in C and C++?
char charTime[] = "TIME"; char buf[] = "SOMETHINGELSE"; C++ and C (remove std:: for C): bool equal = (std::strcmp(charTime, buf) == 0); But the true C++ way: std::string charTime = "TIME", buf = "SOMETHINGELSE"; bool equal = (charTime == buf); Using == does not work because it tries to compare the addresses of the f...
2,440,491
2,440,535
use printf("text %d", number) type format to assign value to variable
I would like to use the syntax that printf uses, using the %d, %s and adding values after to assign a value to a char[]. Is this possible? e.g. Given an output of: printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); I'd like to assign that to char[] outpu...
That should work fine provided you have enough space in the output buffer (at least 26 bytes) to take the largest string you'll create: char output[26]; sprintf(output, "now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); You need: 5 for ...
2,440,979
2,441,028
How to (legitimately) access files after putting self into chrooted sandbox?
Changing a Linux C++ program which gives the user limited file access. Thus the program chroots itself to a sandbox with the files the user can get at. All worked well. Now, however, the program needs to access some files for its own needs (not the user's) but they are outside the sandbox. I know chroot allows acces...
If the files you need to access are within a few directories you could open those directories before you chroot and save the file descriptors. You can then use the so-called *at functions (e.g. openat(), renameat(), etc.) to get at the individual files. Basically you are opening the files relative to the already open...
2,441,009
2,441,024
How to catch the exception in initialization list?
I have a question about how to catch the exception in the initialization list. For example, we have a class Foo derived from Bar class Foo { public: Foo(int i) {throw 0; } } class Bar : public Foo{ public: Bar() : Foo(1) {} }
I think the syntax is like this (even though it's better to catch such things in the caller. And what are you going to do once you caught it?) Bar::Bar() try : Foo(1) { } catch( const SomeException &e ) { }
2,441,045
2,441,066
Bewildering SegFault involving STL sort algorithm
I am trying to recreate the program in Column 15 of programming pearls using the STL. I am trying to create a suffix array using a string and a vector of indices. I record the list of words that I read in a string called input that acts as a list of words separated by ' ' that I read from stdin at the beginning of th...
Most likely your comparator doesn't satisfy strict weak ordering; e.g., it violates transitivity because some ring of values exists such that A < B, B < C, and C < A. Here are the requirements. I don't see it off the top of my head, but I am going to keep staring at it for a few minutes.
2,441,047
2,441,243
How do I set scons system include path
Using scons I can easily set my include paths: env.Append( CPPPATH=['foo'] ) This passes the flag -Ifoo to gcc However I'm trying to compile with a lot of warnings enabled. In particular with env.Append( CPPFLAGS=['-Werror', '-Wall', '-Wextra'] ) which dies horribly on certain boost includes ... I can fix this by ...
There is no built-in way to pass -isystem include paths in SCons, mainly because it is very compiler/platform specific. Putting it in the CXXFLAGS will work, but note that this will hide the headers from SCons' dependency scanner, which only looks at CPPPATH. This is probably OK if you don't expect those headers to eve...
2,441,220
2,441,647
Writing my own iostream utility class: Is this a good idea?
I have an application that wants to read word by word, delimited by whitespace, from a file. I am using code along these lines: std::istream in; string word; while (in.good()) { in>>word; // Processing, etc. ... } My issue is that the processing on the words themselves is actually rather light. The major...
An istream works with a buffer class, so it'll normally read in fairly large chunks (though the exact size isn't guaranteed). As such, you're probably already getting the effect you're looking for. If you handle the buffering on your own, it's somewhat non-trivial -- when you reach the end of a buffer, chances are that...
2,441,269
2,441,284
pthread_create from non-static member function
This is somewhat similiar to this : pthread function from a class But the function that's getting called in the end is referencing the this pointer, so it cannot be made static. void * Server::processRequest() { std::string tmp_request, outRequest; tmp_request = this->readData(); outRequest = this->pars...
You are casting the third argument to a void* ((void*), and then getting an error, as void* cannot be cast to a function pointer. I believe it should compile if you just use &LaunchMemberFunction instead.
2,441,320
2,443,131
VC9 C1083 Cannot open include file: 'boost...' after trying to abstract an include dependency
So I've been working on a project for the past number of weeks and it uses a number of Boost libraries. In particular I'm using the boost::dynamic_bitset library quite extensively. I've had zero issues up until now; but tonight I discovered a dependency between some includes which I had to resolve; and I tried to do so...
So it turns out one of my executables which was using SomeOtherClass did not have the Boost libraries in its include list. I would have realised this earlier if I paid more attention to the output logs. 3>c:.. ClassUsingDynamicBitset.h(2) : fatal error C1083: Cannot open include file: 'boost/dynamic_bitset/dynamic_bit...
2,441,457
2,444,363
Keyboard Input & the Win32 message loop
How do I handle key presses and key up events in the windows message loop? I need to be able to call two functions OnKeyUp(char c); and OnKeyDown(char c);. Current literature I've found from googling has lead me to confusion over WM_CHAR or WM_KEYUP and WM_KEYDOWN, and is normally targeted at PDA or Managed code, where...
Use char c = MapVirtualKey(param,MAPVK_VK_TO_CHAR); to convert virtual key codes to char, and process WM_KEYUP and WM_KEYDOWN and their wParams. if (PeekMessage (&mssg, hwnd, 0, 0, PM_REMOVE)) { switch (mssg.message) { case WM_QUIT: PostQuitMessage (0); notdone = false; ...
2,441,585
2,442,283
dynamic array pointer to binary file
Know this might be rather basic, but I been trying to figure out how to one after create a dynamic array such as double* data = new double[size]; be used as a source of data to be kept in to a binary file such as ofstream fs("data.bin",ios:binary"); fs.write(reinterpret_cast<const char *> (data),size*sizeof(double));...
Hy:) If you use Unix you have some functions: int read(int fd, void *buf, int count);. int write (int fd, void *buf, int nbytes);. The functions are verry fast because are kernel-functions. i run your code and everything was ok : 1 #include <iostream> 2 #include <fstream> 3 #include <cstr...
2,441,659
2,441,706
Dilemma of Sending a Byte Array from JavaScript to COM
I'm having a bit of a problem because neither Javascript nor ActiveX (written in C++) are behaving like good little children. All I'm asking them to do is for Javascript to send a byte array and for the ActiveX to receive the byte array correctly in order to do more computation. This is how I declared my byte array in ...
Arrays in JScript are no distinct types, they are just objects that have a property length and allow access to their contents via properties. In your Invoke()/InvokeEx() method, the VARIANT argument you receive should contain an IDispatch, which represents the scriptable object. On that retrieve the property length and...
2,441,705
2,441,710
I overloaded operator > but it still says no operator matches operands
I need B class to have a min priority queue of AToTime objects. AToTime have operator>, and yet I receive error telling me than there is no operator> matching the operands... #include <queue> #include <functional> using namespace std; class B { public: B(); virtual ~B(); private: log4cxx::LoggerPtr m...
bool operator >(const AToTime& other) It should be a const function. bool operator >(const AToTime& other) const
2,442,081
2,442,572
Convert GUI C++ app to a console one
I have a GUI C++ application (Visual Studio 2008) that needs to be converted to a console one. I don't have any experience in C programming. Mostly I use .NET. Where do I start?
Down-converting a GUI app is major surgery. The programming model is entirely different, a GUI app is event driven. Relying on a message loop to deliver events, processed in message handlers. And typically a bunch of controls that take care of the grunge work of taking input. Given that you have to completely redesi...
2,442,358
2,442,406
Do c++ templates make programs slow?
I have heard from many people that usage of templates make the code slow. Is it really true. I'm currently building a library. There are places where if templates are not created, it would result in code management problem. As of now I can think two solutions to this problem: use #defines Use templates and define all...
The short answer is no. For the longer answer please read on. As others have already noted, templates don't have a direct run-time penalty -- i.e. all their tricks happen at compile time. Indirectly, however, they can slow things down under a few circumstances. In particular, each instantiation of a template (normally)...
2,442,386
2,476,184
Looking for a better way to integrate a static list into a set of classes
I'm trying to expand my sons interest from Warcraft 3 programming into C++ to broaden his horizons to a degree. We are planning on porting a little game that he wrote. The context goes something like this. There are Ships and Missiles, for which Ships will use Missiles and interact with them A Container exists which ...
I think the problem here is that you are stretching the notion of inheritance. What you have is valid code and works but as you point out it doesn't feel right to have a container class hidden behind the scenes of the constructor of your child class. This is (in my opinion) because a Missile doesn't really have anythin...
2,442,473
2,442,541
Split text by whitespaces
I have text file with some text information and i need to split this text at spaces and all word push into List. I make so: QStringList list = line.split(" "); for (int i = 0; i < list.count(); i++){ table.push_back(list[i]); this->ui->textEdit->setText(list[i]); } In line i have my text. But when i...
Try it with: line.split(QRegExp("\\s"));
2,442,518
2,442,667
How to retrieve SID's byte array
How can I convert a PSID type into a byte array that contains the byte value of the SID? Something like: PSID pSid; byte sidBytes[68];//Max. length of SID in bytes is 68 if(GetAccountSid( NULL, // default lookup logic AccountName,// account to obtain SID &pSid // buffer to allocate ...
I think the function you might be looking for is ConvertSidToStringSid. The general idea is to convert the PSID struct to a LPTSTR which is in fact of type wchar_t. You can then convert this using standard functions to a multi-byte char array using wcstombs which will then give you the SID in bytes. Alternatively, you ...
2,442,863
2,442,869
Catching a nested-in-template exception [C++]
I have a problem with writing a catch clause for an exception that is a class nested in a template. To be more specific, I have a following definition of the template and exception: /** Generic stack implementation. Accepts std::list, std::deque and std::vector as inner container. */ template < typename T, ...
Use typename: template <typename Stack> void testTopThrowsStackEmptyExceptionOnEmptyStack() { Stack stack; std::cout << "Testing top throws StackEmptyException on empty stack..."; try { stack.top(); } catch (typename Stack::StackEmptyException) { // as expected. } std::cout << ...
2,443,064
2,443,501
Interaction between C++ and Rails applications
I have two applications: c++ service and a RoR web server (they are both running at same VPS) I need to "send" some variables (and then do something with them) from each other. For exaple, i'm looking for something like this: // my C++ sample void SendMessage(string message) { SendTo("127.0.0.1", message); } void G...
Ok, i have found the solution. Its TCP sockets: Ruby TCP server, to send messages: require 'socket' server = TCPServer.open(2000) loop { Thread.start(server.accept) do |client| client.puts(Time.now.ctime) client.puts "Closing the connection. Bye!" client.close end ...
2,443,079
2,443,101
c/c++ how to convert short to char
I am using ms c++. I am using struct like struct header { unsigned port : 16; unsigned destport : 16; unsigned not_used : 7; unsigned packet_length : 9; }; struct header HR; here this value of header i need to put in separate char array. i did memcpy(&REQUEST[0], &...
Sounds like the expected behaviour with your struct as you defined packet_length to be 9 bits long. So the lowest bit of its value is already within the fifth byte of the memory. Thus the value -128 you see there (as the highest bit of 1 in a signed char is interpreted as a negative value), and the value 15 is what is ...
2,443,165
2,443,379
Has the small object allocator found in "Modern C++ Design"/Loki been deprecated in favor of newer implementations?
It seems the code and the book have been relegated to the foundation of the movement of modern C++, and isn't updated any more. Is there some kind of replacement for this in Boost or TR1?
Check out the Boost.Pool library.
2,443,166
2,443,191
C language program is detected as a virus
#include<stdio.h> #include<conio.h> union abc { int a; int x; float g; }; struct pqr { int a; int x; float g; } ; void main() { union abc b; struct pqr c; clrscr(); b.a=10; textbackground(2); textcolor(6); cprintf(" A = %d",b.a); printf("\nUnion = %d",sizeof(b)); printf("\nStructure = ...
Looks like a false-positive. Because modern viruses use polymorphism to hide from anti-virus programs, the anti-virus program has to report even partial matches, and apparently your compiler with the given source code produces a partial match to that malware.
2,443,288
2,443,376
Objective-C @class / import best practice
I've noticed that a lot of Objective-C examples will forward declare classes with @class, then actually import the class in the .m file with an import. I understand that this is considered a best practice, as explained in answers to question: @class vs. #import Coming from C++ this feels backwards. I would normally i...
To be honest, your C++ is actually backwards. Generally in C++ you want to avoid headers being included inside other headers preferring forward declarations to includes. This is generally considered the best practice because it decreases compile time, and shrinks the size of the preprocessed code files fed into the com...
2,443,316
2,443,334
C++ random number from a set
Is it possible to print a random number in C++ from a set of numbers with ONE SINGLE statement? Let's say the set is {2, 5, 22, 55, 332} I looked up rand() but I doubt it's possible to do in a single statement.
Say these numbers are in a set of size 5, all you gotta do is find a random value multiplied by 5 (to make it equi probable). Assume the rand() method returns you a random value between range 0 to 1. Multiply the same by 5 and cast it to integer you will get equiprobable values between 0 and 4. Use that to fetch from t...
2,443,353
2,443,357
How to override virtual function in good style? [C++]
guys I know this question is very basic but I've met in few publications (websites, books) different style of override virtual function. What I mean is: if I have base class: class Base { public: virtual void f() = 0; }; in some publications I saw that to override this some authors would just say: void f(); and ...
This is purely a matter of taste. Some weak arguments can be made back and forth as to the self-documentation value of some styles versus the non-redundancy of others.
2,443,358
2,448,473
How to add lines numbers to QTextEdit?
I am writing a Visual Basic IDE, and I need to add lines numbers to QTextEdit and highlight current line. I have found this tutorial, but it is written in Java and I write my project in C++.
Here's the equivalent tutorial in C++: Qt4: http://doc.qt.io/qt-4.8/qt-widgets-codeeditor-example.html Qt5: http://doc.qt.io/qt-5/qtwidgets-widgets-codeeditor-example.html
2,443,372
2,443,410
inline and member initializers
When should I inline a member function and when should I use member initializers? My code is below.. I would like to modify it so I could make use some inline when appropriate and member initializers: #include "Books.h" Book::Book(){ nm = (char*)""; thck = 0; wght = 0; } Book::Book(const char *name, int thickne...
Short member functions that are called frequently are good candidates for inlining. In order to make the member function "inlinable," you need to define it in the header file (either in the class definition itself, or below the class definition using the inline keyword). You should always use constructor initializer l...
2,443,431
2,443,458
Project-wide additional library paths -- MSVS2008
I'm setting up a VC++ project in MS Visual Studio 2008 that'll be used by several people. I wanted to keep things as simple as possible so I've set up Additional Include Directories via the Project properties. I've also set up additional library files via Tools -> Options -> Projects and Solutions -> VC++ Directories. ...
You can set additional library paths in your project properties: Project Properties | Configuration Properties | Linker | General | Additional Library Directories
2,443,479
2,443,516
C++, how implicit conversion/constructor are determined?
How does C++ determine implicit conversion/construction of objects few levels deep? for example: struct A {}; struct B: A {}; struct C { operator B() { return B(); } }; void f(A a) {} int main(void) { f(C()); } Does it create tree of all possible conversions and chooses appropriate terminal? Something else? Than...
The call to f() would need two conversions, one user-defined conversion (C to B) and one built-in conversion (derived-to-base: B to A). Calls with non-matching arguments succeed when they would need zero or one user-defined conversions. If different conversions (built-in or user-defined) would succeed, then, if all pos...
2,443,701
2,443,748
Piping EOF problems with stdio and C++/Python
I got some problems with EOF and stdio in a communication pipeline between a python process and a C++ program. I have no idea what I am doing wrong. When I see an EOF in my program I clear the stdin and next round I try to read in a new line. The problem is: for some reason the getline function immediatly (from the sec...
communicate in python is a one shot function. It sends the given input to a process, closes the input stream, and reads the output streams, waiting for the process to terminate. There is no way you can 'restart' the pipe with the same process after "communicating". Conversely, on the other side of the pipe, when you re...
2,443,738
2,445,047
C++ TerminateProcess function
I've been searching examples for the Win32 API C++ function TerminateProcess() but couldn't find any. I'm not that familiar with the Win32 API in general and so I wanted to ask if someone here who is better in it than me could show me an example for, Retrieving a process handle by its PID required to terminate it and ...
To answer the original question, in order to retrieve a process handle by its PID and call TerminateProcess, you need code like the following: BOOL TerminateProcessEx(DWORD dwProcessId, UINT uExitCode) { DWORD dwDesiredAccess = PROCESS_TERMINATE; BOOL bInheritHandle = FALSE; HANDLE hProcess = OpenProcess(...
2,443,911
2,444,213
std::string constructor corrupts pointer
I have an Entity class, which contains 3 pointers: m_rigidBody, m_entity, and m_parent. Somewhere in Entity::setModel(std::string model), it's crashing. Apparently, this is caused by bad data in m_entity. The weird thing is that I nulled it in the constructor and haven't touched it since then. I debugged it and put a w...
Your problem is that this line is constructing a nameless temporary GEntity inside the constructor body for a different GEntity. The temporary is then thrown away once the statement completes and no further initialization of the non-temporary GEntity is performed. GEntity(world, idNum, btTransform::getIdentity()); If ...
2,444,085
2,444,099
alternative to strdup
I'm writing a C++ class for a book that contains a name: class Book { private: char* nm; .......... ............ .......... ........... }; I am not allowed to use std::string in this assignment. So here I am using strdup to copy the value of the parameter name into nm in the constructor: Book::Book(const char *na...
Strictly speaking: The string class is part of the Strings library. This is much easier to use, dynamic in nature and you have less worry when copying/assigning than C-style strings. The other approach is to manually copy out: class Book { public: Book(const char *name, ...) : nm(0), ... { if (!name)...
2,444,148
2,449,152
GDI+ Load a jpg and save as 24bit png problem
Problem Hello all! I have this code which takes my jpg image loops through altering pixels and finally saving it as a png type. The problem is that the resulting image has a bit depth of 32 bits. I need it to be 24 bit, can any one shiny some light on the correct method of setting it? Am I along the right tracks lookin...
Ok I actually fixed it, I've used the LockBits() to access the bits directly and modify them, this gives me a much needed performance boost and keeps it as a 24bit image. static inline void Brighten(Gdiplus::Bitmap* img) { int width = img->GetWidth(),height = img->GetHeight(),r,g,b; Gdiplus::Rect rect(0,0,wi...
2,444,351
2,444,355
A 16-digit hashing function
Is there a hash function that returns a 16-digit hex value (as MD5 returns 32-digit), or is there a library (for C++) in which I can use MD5 or SHA-1 which returns a 16-digit value
Since you're willing to live with the much-higher collision rate, you can just truncate the MD5 hash of the data.
2,444,428
2,454,874
Need help modifying C++ application to accept continuous piped input in Linux
The goal is to mine packet headers for URLs visited using tcpdump. So far, I can save a packet header to a file using: tcpdump "dst port 80 and tcp[13] & 0x08 = 8" -A -s 300 | tee -a ./Desktop/packets.txt And I've written a program to parse through the header and extract the URL when given the following command: cat ~...
You're going to have to make some bigger changes to get it to work. Your getline delimited by '\0' won't terminate until it either sees a '\0' (which isn't going to happen) or the input reaches EOF. That's why it works when you use a file (which eventually reaches EOF) but not with streaming straight from tcpdump. I'...
2,444,514
2,444,521
Why do programmers sometimes refer to "C++/STL" like it's a separate language?
This may seem a trivial question, but it's one that's bothered me a lot lately. Why do some programmers refer to "C++/STL" like it's a different language? The STL is part of the C++ standard library -- and therefore is part of the language, "C++". It's not a separate component, and it does not live alone in the scope o...
An understanding of the STL isn't necessary to understand C++. It's useful to have when you need ADTs, but you can go (could have gone?) through your whole C++ career without needing it.
2,444,650
2,444,682
Colour instead of color?
I'm working on a game engine in C++ and I have methods like setColour and things that use British grammar. While I was thinking how C++ compilers mostly use the English language (correct me if I'm wrong) and how most APIs use American grammar, should I go with the flow and continue the unofficial standard in the gramma...
You should use the American spelling of color. 99% of code out there uses this, even including much of the code written by British or Australian English speakers. If you use something different, you (or someone else that uses your code) are just going to end up forgetting which to use at some point and making a needles...
2,444,695
2,444,706
volatile vs. mutable in C++
I have a question about the difference between volatile and mutable. I noticed that both of the two means that it could be changed. What else? Are they the same thing? What's the difference? Where are they applicable? Why the two ideas are proposed? How to use them in different way? Thanks a lot.
A mutable field can be changed even in an object accessed through a const pointer or reference, or in a const object, so the compiler knows not to stash it in R/O memory. A volatile location is one that can be changed by code the compiler doesn't know about (e.g. some kernel-level driver), so the compiler knows not to...
2,444,843
2,444,876
why nResult != nConvertedLen,when use CComBSTR;
CComBSTR wsData = (char*)pvData; when constuct CComBSTR,call A2WBSTR,but sometimes nResult != nConvertedLen,just 1/20. why? inline BSTR A2WBSTR(_In_opt_ LPCSTR lp, int nLen = -1) { if (lp == NULL || nLen == 0) return NULL; USES_CONVERSION_EX; BSTR str = NULL; #pragma warning(push) #pragma warning(d...
My best guess is that there are multi-threading issues involved. As you can see both nResult and nConvertedLen are results to calls to MultiByteToWideChar with the same source string. The first call is used to simply determine the length of the buffer that needs to be allocated to return the result of the conversion. M...
2,444,933
2,444,940
One question with array declaration in C++
What's the difference between the two code below. int a[] = {0,0}; int a[2] = {0,0}; It seems I can assign value to a[3] in both cases. I can access a[3] in any case. So what's the difference?
There is no difference. In the first one, the compiler does the counting for you, which is nice if you decide to change the number of elements later on. The fact that your compiler forgives you for assigning to or using a[3] doesn't mean that doing so is correct. In fact, you can't even access a[2] since it only has ...
2,445,050
2,445,071
How different is Objective-C from C++?
What are the main differences between Objective-C and C++ in terms of the syntax, features, paradigms, frameworks and libraries? *Important: My goal is not to start a performance war between the two languages. I only want real hard facts. In fact, my question is not related to performance! Please give sources for anyth...
Short list of some of the major differences: C++ allows multiple inheritance, Objective-C doesn't. Unlike C++, Objective-C allows method parameters to be named and the method signature includes only the names and types of the parameters and return type (see bbum's and Chuck's comments below). In comparison, a C++ memb...
2,445,143
2,445,182
How does void QTableWidget::setItemPrototype ( const QTableWidgetItem * item ) clones objects?
QTableWidget::setItemPrototype says following. "The table widget will use the item prototype clone function when it needs to create a new table item. For example when the user is editing in an empty cell. This is useful when you have a QTableWidgetItem subclass and want to make sure that QTableWidget creates instances ...
QTableWidgetItem::clone() is a virtual member function and has to be reimplemented by subclasses of QTableWidget. Thus, when clone() is called, the implementation of clone() in the subclass is getting invoked, and in the subclass, the correct type is of course known.
2,445,469
2,445,486
Why cant we initialize Const and reference varibales inside the constructor braces({ }) and is always done via initialization list
Why cant we initialize Const and reference varibales inside the constructor braces({ }) and is always done via initialization list Thanks, Sandeep
The lifetime for a reference begins after it's initialized (like all variables), and once it's initialized it represents an alias to another variable. Consider: int& x; /// ... SomeClassConstructor(void) { // initialization list is done, reference lifetime has begun, and // therefore is an alias. It already must al...
2,445,476
2,445,851
Ruby on Rails, PHP or C++ for web social network
I have chosen diploma work in university. It's a mini social network. But now I am really stuck with which technology I should stick. I am average at C++ ISAPI web services development, below average PHP(had few projects with it) and new to Ruby and its framework RAILS. I have a deadline 1.5 month to develop it(about 5...
Definitely not C++. I work with C++, Ruby, PHP, Ruby on Rails, CakePHP, CodeIgniter and Kohana. Since C++ is more similar to PHP than Ruby and you have little time to learn, I would go with a PHP framework. Every now and then I like to make little social networks in my local machine , I would recommend that you got wit...
2,445,514
2,445,552
Returning recursive ternary freaks out
assume this following function: int binaryTree::findHeight(node *n) { if (n == NULL) { return 0; } else { return 1 + max(findHeight(n->left), findHeight(n->right)); } } Pretty standard recursive treeHeight function for a given binary search tree binaryTree. Now, I was helping a friend (he's...
Macros are expanded by the preprocessor, before the compiler gets to see the code. This means that, for example, macro parameters might be evaluated more than once. With your macro, you're going to end up with something akin to: int binaryTree::findHeight(node *n) { if (n == NULL) { return 0; } else { ...
2,445,543
2,445,811
C++ for Ruby scripters
I am a fairly capable Ruby scripter/programmer, but have been feeling pressure to branch out into C++. I haven't been able to find any sites along the lines of "C++ for Ruby Programmers". This site exists for Python (which is quite similar, I know). Does anyone know of a guide that can help me translate my Ruby 'though...
I don't think that language introductions written specifically for migrants from a certain language have considerable advantage over traditional "independent" introductory books. Reading as a cognitive process has a great feature: reading speed varies greatly. That means that you should take any good C++ book (I'm sure...
2,445,760
2,454,607
Vim plugin for updating C++ function definition
I'm looking for a Vim plugin that can do these kind of thing. Let's say I have a function in a .cpp file void myFunction(int arg1, int arg2, int arg3){ //code } The function definition is defined in the .h file. So every time I change the function name or add a new argument to the function, I have to go back the t...
It sounds to me like you are looking for a C++ refactoring tool. A quick search for 'refactor' on vim.org brought up one script specifically meant for C/C++ but it doesn't have a very high rating.
2,445,771
2,445,783
Function return type style
I'm learning c++0x, at least the parts supported by the Visual C++ Express 2010 Beta. This is a question about style rather than how it works. Perhaps it's too early for style and good practice to have evolved yet for a standard that isn't even released yet... In c++0x you can define the return type of a method using -...
Do not be style-consistent just for being consistent. Code should be readable, i.e. understandable, that's the only real measure. Adding clutter to 95% of the methods to be consistent with the other 5%, well, that just does not sound right to me.
2,445,820
2,445,867
DST change handling in a daemon process (*NIX)
In a *NIX environment, if I have a 24x7 running application, how do I handle DST changes? I am looking for a solution for my app written in C/C++.
Why would a deamon use anything else that UTC time?
2,445,868
2,445,876
Is select() Ok to implement single socket read/write timeout?
I have an application processing network communication with blocking calls. Each thread manages a single connection. I've added a timeout on the read and write operation by using select prior to read or write on the socket. Select is known to be inefficient when dealing with large number of sockets. But is it ok, in te...
Yes that's no problem, and you do want some timeout mechanisms to not leak resources from bad behaving clients etc. Note that having a large number of threads is even more inefficient than having select dealing with a large number of sockets.
2,445,899
2,446,020
Does operator new allocate on THREAD heap?
My problem seems to be this: heap data allocated by one thread (that later dies) seems to die as well. As so: Thread X: starts Thread Y: starts Thread X: ptr = new some bytes Thread X: dies Thread Y: tries to use ptr - and crashes! So far, I've only seen this problem on Darwin (Mac OS 10.5 and 10.6), but haven't trie...
Do threads have a distinct heap? This thread has some good information regarding this subject
2,446,142
2,446,159
How to differentiate two constructors with the same parameters?
Suppose we want two constructors for a class representing complex numbers: Complex (double re, double img) // construct from cartesian coordinates Complex (double A, double w) // construct from polar coordinates but the parameters (number and type) are the same: what is the more elegant way to identify what is intend...
It is better to add static methods with appropriate names and let them to create the objects. static Complex createFromCartesian(double re, double img); static Complex createFromPolar(double A, double w);