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
1,349,530
1,349,781
Loader lock (regsvr32 R6033 error) with managed C++ dll
I have a C++ dll which implements several COM interfaces, that I'm trying to migrate to managed C++. I set the /clr compiler flag and changed the Runtime Library property from /MT to /MD to avoid the conflict between these two flags, but that's all I've changed. When it attempts to register the dll during the build p...
You need to add the /clr compiler flag only to the files that use managed code and not for the whole project. This is what the Visual Studio "Wizard" does, here is how I've tested: Create a Visual C++ ATL Project Added a ATL Simple Object, in order to have a COM interface (Project->Add Class) Added a CLR Component Cla...
1,349,734
1,349,748
Why would anyone use set instead of unordered_set?
C++0x is introducing unordered_set which is available in boost and many other places. What I understand is that unordered_set is hash table with O(1) lookup complexity. On the other hand, set is nothing but a tree with log(n) lookup complexity. Why on earth would anyone use set instead of unordered_set? i.e is there a ...
When, for someone who wants to iterate over the items of the set, the order matters.
1,350,243
1,350,255
Why does the C++ ofstream write() method modify my raw data?
I have a jpeg image in a char[] buffer in memory, all I need to do is write it out to disk exactly as is. Right now I'm doing this ofstream ofs; ofs.open(filename); ofs.write(buffer, bufferLen); ofs.close(); but the image doesn't come out right, it looks garbled with random black and white stripes everywhere. After c...
Set the mode to binary when you open the file: http://www.cplusplus.com/reference/iostream/ofstream/ofstream/
1,350,271
1,350,285
In C++ how to return index of an array if user entered matches entered array?
I wanted to know how can we get the index of the array if the user entered array matches the input array ? For example: Input Array = [1,2,3,4] and user entered Array = [2,3] than I should get output as index where both array matches is 1. Guidance would be highly appreciated.
Use the STL search algorithm, which does just what you want: "The search() algorithm looks for the elements [start2,end2) in the range [start1,end1)." You'll need to supply it pointers to the start and end of the two arrays; you get the end pointer for an array by adding its length to its start pointer. Better, use the...
1,350,288
1,350,303
Static local in class member function survives class reallocation?
class Foo { public: void bar(); }; void Foo::bar() { static int n = 0; printf("%d\n", n++); } int main(int argc, char **argv) { Foo *f = new Foo(); f->bar(); delete f; f = new Foo(); f->bar(); delete f; return 0; } Does n reset to 0 after delete'ing and new'ing the class ove...
As the variable is static in the function, it will be 0, 1 as the memory is not delete as it is static, even if the variable is part of a function and not part of the class. Even when you delete an instance of a class, the functions still remain in memory for the class as they can be used by other instances of the clas...
1,350,380
1,350,411
problems using STL std::transform from cygwin g++
I am running g++(gcc version 3.4.4) on cygwin. I can't get this small snippet of code to compile. I included the appropriate headers. int main(){ std::string temp("asgfsgfafgwwffw"); std::transform(temp.begin(), temp.end(), temp.begin(), std::toupper); ...
This explains it quite well. Which will boil down to this code: std::transform(temp.begin(),temp.end(),temp.begin(),static_cast<int (*)(int)>(std::toupper));
1,350,396
1,350,407
Error while inserting pointer to a vector
I have the following CPP code snippet and the associated error message: Code snippet struct node{ char charVal; bool childNode; struct node *leftChild; struct node *rightChild; }; vector<std::pair<int,struct node*> > nodeCountList; struct node *nodePtr = n...
You need to push a std::pair. nodeCountList.push_back(std::make_pair(1,nodePtr));
1,350,410
1,350,500
Have you heard of C++ Server Pages?
I have been looking for a ways to maximize speed in my web application. Came across an interesting application called CSP. Have you guys ever heard of them? They claim that you can program web application in c++. Is it worth it? http://www.micronovae.com/CSP.html
...Is it worth it? It depends on what you're trying to do. Most web applications are built with little or no regard for performance. The majority of pages do not need CGI at all. Using a database and code to produce/modify the page makes sense but serving pages to clients by generating each time is not optimum. As stat...
1,350,528
1,351,815
Initializing a vector with stream iterators
I'm trying to initialize a vector using iterators and I'm getting a compiler error basically saying that there's no matching function to call. The code reads from a file with an istream_iterator and ends with an input sentinel. Then I try to initialize the vector with those two iterators. #include "std_lib_facilities....
The book header had some kind of compliance issues, so I just included the appropriate headers and it worked.
1,350,532
1,350,807
Way to determine proper predicate for templated types
Suppose I have a function which looks like this: template <class In, class In2> void func(In first, In last, In2 first2); I would like this function to call another function which accepts a predicate. My initial instinct was to do something like this: template <class In, class In2> void func(In first, In last, In2 fir...
I seemed to remember that there was a traits for this in boost, but I can't find it after a quick search. If you are no more successful than me, you can construct it yourself, template <typename T1, typename T2> struct least_common_promotion; template <> struct least_common_promotion<short, int> { typedef int typ...
1,350,593
1,350,916
Finding the Difference between the contents in two Files
I am developing a Application which takes two Files and output will be two files which will have only the contents which differs in both the files. The application is developed using VC++ My Files are of Html type Is there any library which will do the diff opereation between two files
WinMerge is a Windows differencing and merging tool. It uses diffutils, written using VC++, and it's open source.
1,350,657
1,350,946
variable parameter function, how to make it type safe and more meaningful?
I am a newer for C++, and my first language is Chinese, so my words with English may be unmeaningful, say sorry first. I know there is a way to write a function with variable parameters which number or type maybe different each calling, we can use the macros of va_list,va_start and va_end. But as everyone know, it is t...
You can do something like this: template <typename T> class sum{ T value; public: sum () : value() {}; // Add one argument sum<T>& operator<<(T const& x) { value += x; return *this; } // to get funal value operator T() { return value;} // need another ...
1,350,819
1,350,833
C++, Free-Store vs Heap
Dynamic allocations with new/delete are said to take place on the free-store,while malloc/free operations use the heap. I'd like to know if there is an actual difference, in practice. Do compilers make a distinction between the two terms? (Free store and Heap, not new/malloc)
See http://www.gotw.ca/gotw/009.htm; it can describe the differences between the heap and the free-store far better than I could: Free-store: The free store is one of the two dynamic memory areas, allocated/freed by new/delete. Object lifetime can be less than the time the storage is allocated; that is, free ...
1,350,994
1,351,902
Is it safe to read an integer variable that's being concurrently modified without locking?
Suppose that I have an integer variable in a class, and this variable may be concurrently modified by other threads. Writes are protected by a mutex. Do I need to protect reads too? I've heard that there are some hardware architectures on which, if one thread modifies a variable, and another thread reads it, then the r...
atomic read As said before, it's platform dependent. On x86, the value must be aligned on a 4 byte boundary. Generally for most platforms, the read must execute in a single CPU instruction. optimizer caching The optimizer doesn't know you are reading a value modified by a different thread. declaring the value volatile ...
1,351,129
1,351,650
Calculating 3D tangent space
In order to use normal mapping in GLSL shaders, you need to know the normal, tangent and bitangent vectors of each vertex. RenderMonkey makes this easy by providing it's own predefined variables (rm_tangent and rm_binormal) for this. I am trying to add this functionality to my own 3d engine. Apparently it is possible t...
Found the solution. Much simpler (but still a little hacky) code: void CalculateTangentSpace(void) { float x1 = m_vertices[1]->m_pos->Get(0) - m_vertices[0]->m_pos->Get(0); float y1 = m_vertices[1]->m_pos->Get(1) - m_vertices[0]->m_pos->Get(1); float z1 = m_vertices[1]->m_pos->Get(2) - m_vertices[0]->m_pos-...
1,351,199
1,351,390
How can I create a static object member of class?
I am fairly new to c++, especially in its techniques. My question is, how can I create a static object member of a class itself. What I mean is I declared a static member object inside a class. Example: CFoo:CFoo *pFoo[2] = {0}; class CFoo { public: static CFoo *pFoo[2]; public: CFoo(int a); public: CFoo *get...
Let's improve your code one step at a time. I'll explain what I'm doing at each step. Step 1, this isn't Java. You don't need to specify public for every member. Everything after public: is public until you specify something else (protected or private). I also moved the definition of pFoo after the class. You can'...
1,351,217
1,351,422
QThread::wait() and QThread::finished()
Does QThread::wait() return (i.e., unblocks execution) after calling all the slots that were associated with QThread::finished() signal? Thanks in advance.
No, it may return before, during or after a slot associated with signal finished() is being executed. This depends on the type of signal-slot connection, read about queued connections and direct connections.
1,351,381
1,351,398
FFT Problem (Returns random results)
I've got this code, but it keeps returning random frequencies from 0 to about 1050. Please can you help me understand why this is happening. My data length is 1024, sample rate is 8192, and data is a short array filled with input data from the mic. float *iSignal = new float[2048]; float *oSignal = new float[2048]; in...
Assuming oSignal is filled with complex numbers in such a way, that real and imaginary parts alternate, it might help to change for(int y=0;y< 8191;y++) to for(int y=0;y< 8191;y+=2) Edit: I didn't even notice that you're passing only 1024 samples. You must pass as many time-domain samples as there will be frequency-d...
1,351,418
1,352,237
Adding VC++ to Eclipse toolchain
I want to write a program to link with binaries already created with VC++. What are the steps to add a toolchain for VC++ in Eclipse? Has anyone tried it successfully? If so, does the debugger still work?
There is a toolchain implementation for VC++. The build plugin is called org.eclipse.cdt.msw.build, and there is a set of debugger plugins called org.eclipse.cdt.msw.debug.*. I think the build integration works, but the debugger integration still needs some work before it is usable. Doug Schaefer on the CDT team has bl...
1,352,095
1,352,111
typechecking provided on enum
I would expect the following code snippet to complain about trying to assign something other that 0,1,2 to a Color variable. But the following does compile and I get the output Printing:3 3 Can anybody explain why? Is enum not meant to be a true user-defined type? Thanks. enum Color { blue=0,green=1,yellow=2}; void p...
Since you manually cast the 3 to Color, the compiler will allow you to do that. If you tried to initialize the variable x with a plain 3 without a cast, you would get a diagnostic. Note that the range of values an enumeration can store is not limited by the enumerators it contains. It's the range of values of the smal...
1,352,334
1,352,684
QCalendarWidget as "Pop-up", not as new Window?
I want to create a Settings-Widget, where I can choose a Date. Because it isn't nice to create 3 QLineEdits to call the QDate-Constructor with QDate(int year, int month, int day), I thought it would be better, if you can push a "show calendar"-Button for example, where you can choose the date. But I don't want to show ...
For an alternate option, have you considered using QDateEdit? It will allow your users to edit the date in a format that is consistent with the rest of the operating system.
1,352,370
1,352,376
C Static Array Initialization - how verbose do I need to be?
To initialize an int array with all zeros, do I need to use: int foo[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Or, will this work: int foo[10] = {0};
int foo[10] = {0}; This is very fine :) Note that if you do the following: int foo[10] = {1}; Only the first element of the array will be initialized with the non-zero number whereas the rest will be initialized with zeros.
1,352,483
1,353,001
Protect private key in Qt application
I have a Qt application written in C++ that uses a SSL-connection (QSslSocket) with another application for extra security. However, the application has a private key embedded in it. With applications like Process Explorer it's really easy to fish out the private key. (Properties of file -> Strings) Security is not ver...
You may need of solutions to your problem from a different angle. I agree with Shoosh's answer in that no matter what you do a person with the right tools and knowledge will be able to break your code and figure out your private key. What you need to do is either externalize the data or mitigate the risks if your pri...
1,352,571
1,352,630
What's the difference between C++0x concepts and The Boost Concept Check Library (BCCL)?
Concepts didn't make the C++0x standard, but Boost still provides The Boost Concept Check Library (BCCL). I guess that BCCL doesn't cover everything that was meant to into the C++0x standard. What is the difference between BCCL and the proposed C++0x solution?
Checking the template definition A big difference of concepts to these manual solutions is that concepts allow the definition of a template to be type-checked without doing anything special. The concept check library allows only the *use* of it to be type checked (unless you manually write test-instantiation types or m...
1,352,732
1,352,824
What do these C++ code snippets do?
#ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif Why define these tags? CSortHeaderCtrl::CSortHeaderCtrl() : m_iSortColumn( -1 ) , m_bSortAscending( TRUE ) { } What are the two functions after colon used for? BEGIN_MESSAGE_MAP(CSortHeaderCtrl, CHeader...
Why define these tags ? See jcopenha's answer. What is the two functions after colon used for ? See Peter's answer. Is there any similar things in C# like this ? What's this used for ? In C# it might be implemented as a dictionary of delegates. It's called a "message map" (probably described in one of the subsect...
1,352,784
1,352,791
Preprocessor examples in C language
I want some examples of C preprocessor directives, such as: #define pi 3.14 #define MAX 100 I know only this. I want to know more than this, more about preprocessor directives.
The biggest example would be #include<stdio.h> But there are a fair amount. You can also define macros: #define MAX(X,Y) (((X) > (Y)) ? (X) : (Y)) And use header guards #ifndef A_H #define A_H // code #endif There are proprietary extensions that compilers define to let you give processing directives: #ifdef WIN...
1,352,875
1,353,512
Naming convention for a variable that works like a constant
I have a variable that I'm using like a constant (it will never change). I can't declare it as a constant because the value gets added at runtime. Would you capitalize the variable name to help yourself understand that data's meaning? Or would you not because this defies convention and make things more confusing? The l...
Encapsulate it. #include <iostream> class ParamFoo { public: static void initializeAtStartup(double x); static double getFoo(); private: static double foo_; }; double ParamFoo::foo_; void ParamFoo::initializeAtStartup(double x) { foo_ = x; } double ParamFoo::getFoo() { return...
1,352,959
1,352,969
Using COM object from C++ that in C#.NET returns object []
I have a COM object that I'm trying to use from C++ (not .NET), and all of the example programs and manual are written assuming the use of C#.NET or VB.NET. COM is new to me so I'm a bit overwhelmed. I'm using #import on the TLB but am struggling to deal with the variants that are used as parameters. I have one particu...
Typically, you look at the vt member of the variant to see what type of thing it actually is. In this case I would expect it to be an array, so you would expect that the vartype would be some variation on VT_ARRAY (usually it is bitwise OR'ed with the type of the members). Then, you get the parray member which contains...
1,353,118
1,353,140
How to set sockets to blocking mode in Windows?
I'm doing some fairly simple cross-platform TCP socket programming. I have unfortunately found out that when compiled on Windows, my sockets are non-blocking by default, while on OS X they are blocking by default. How do I force a socket into blocking mode on Windows? Do they normally default to non-blocking mode or is...
I believe this reference may help; note, in particular, that Although blocking operations on sockets are supported under Windows Sockets, their use is strongly discouraged. Programmers who are constrained to use blocking mode -- for example, as part of an existing application which is to be ported -- sho...
1,353,144
1,354,058
Subclassing a window with a functor (Win32)
Quick sanity check: Is it possible to subclass a window using a functor? I'm running into a situation where I want to have some data available in the win proc, but GWLP_USERDATA is already being used. A functor seems like a good alternative, but I'm having trouble getting it to work. Here's the basics: class MyWinProc ...
GWLP_USERDATA is not the only way to store data associated with a window, you can also use SetProp(). And at least on x86, you can do ATL style thunking (A small piece of asm code that puts your class pointer in ecx and then jumps to your wndproc) You can find some links about that in a answer I posted here
1,353,161
1,353,442
What's the easiest way to call Postgres from a MinGW program?
All I need is get MinGW talking to Postgres. I've considered several options: Use libpq. The libpq.lib that comes with Postgres for Windows links okay, but crashes when I use the library. I think because it was compiled for VC++. I can't find just the libpq code, so I'd have to recompile the entire Postgres tree i...
You can rebuild just libpq if you have to. Run "./configure" and then run "make" in just src/interfaces/libpq. But really, the msvc built libpq should work just fine with mingw. It's just a standard Windows DLL. It may be an issue with the .lib - but the DLL should be fine. AFAIK, only the PQtrace() functionality will ...
1,353,263
1,353,284
How to unblock ConnectNamedPipe and ReadFile? [C#]
I have a class (NamedPipeManager) which has a thread (PipeThread) that waits for a NamedPipe connection using (ConnectNamedPipe) and then reads (ReadFile) - these are blocking calls (not-overlapped) - however there comes a point when I want to unblock them - for example when the calling class tries to stop the NamedPip...
Starting with Windows Vista, there is a CancelSynchronousIO operation available for threads. I don't think there is a C# wrapper for it, so you would need to use PInvoke to call it. Before Vista, there isn't really a way to perform such an operation gracefully. I would advise against using thread cancellation (which mi...
1,353,384
1,353,397
"l-value required" error
When do we get "l-value required" error...while compiling C++ program???(i am using VC++ )
An "lvalue" is a value that can be the target of an assignment. The "l" stands for "left", as in the left hand side of the equals sign. An rvalue is the right hand value and produces a value, and cannot be assigned to directly. If you are getting "lvalue required" you have an expression that produces an rvalue whe...
1,353,421
1,353,425
The right way to create pointer to pointer object?
What is the right way to create a pointer to pointer object? Like for example, int **foo; foo = new int[4][4]; Then the compiler gives me an error saying "cannot convert from int (*)[4] to int **. Thanks.
int **foo = new int*[4]; for (int i = 0; i < 4; i++) foo[i] = new int[4]; Clarification: In many languages the code above is called a jagged array and it's only useful when the "rows" have different sizes. C++ has no direct language support for dynamically allocated rectangular arrays, but it's easy to write it you...
1,353,757
1,353,816
How do I refer to std::sin(const valarray<double> &)?
I'm having trouble with some valarray function pointer code: double (*fp)(double) = sin; valarray<double> (*fp)(const valarray<double> &) = sin; The first compiles, the second gives: error: no matches converting function 'sin' to type 'class std::valarray<double> (*)(const class std::valarray<double>&)'
This compiles, using the __typeof__ GCC extension. Looks like GCC's valarray uses expression templates to delay calculation of the sinus. But that will make the return type of the sin template not exactly valarray<T>, but rather some weird complex type. #include <valarray> template<typename T> struct id { typedef T t...
1,353,769
1,353,906
Haxe - Generating Exe's (cpp)
I've been instructed to download and install FlashDevelop and it seems fine but I don't know how to generate exe files when writing programs in Haxe. I try to Build or Run the project in FlashDevelop BUT it just doesn't do anything. Can anybody please advise me on how to do this? Thank you
The CPP target is the youngest in the Haxe world and so still a little rough on the edges; add in more complexity because it depends on external tools to properly work. Made that premise, try to create a new Haxe/CPP project in FlashDevelop, open the Main class and add a simple trace("hello world!"); line. Hit F5 to s...
1,353,973
1,353,981
C++ template, linking error
I have a problem in calling a template class I have. I declared a new type name Array, which is a template; In the .hpp file: template <typename T> class Array { public: Array(); }; In the .cpp file: template <typename T> Array<T>::Array() { //Do something } In main: Array<int> arr; I get Linkage error: unresolve...
Template functions, including member functions, must be written entirely in the header files. This means that if you have a template class, its implementation must be entirely in a header file. This is because the compiler needs to have access to the entire template definition (not just the signature) in order to gener...
1,354,026
1,354,104
CEvent-like behaviour with Boost.Thread
Problem in words: For my application, I have a class that reads from a serial port. It uses Windows primitives for COM port handling and had a thread for asynchronous reading. I'm trying to convert this away from Windows primitives using Boost libraries such as Boost.Asio and Boost.Thread. In the Windows port, my IO ...
As you said, to resemble a windows style event you need a condition-variable plus a boolean flag. Of course you can combine several boolean flags into one if it satisfies your needs. However, the problem you mentioned (condition variables never get an active state where wait will immediately return) is usually solved ...
1,354,124
1,370,611
C++ ctype facet for UTF-8 in mingw
In a project all internal strings are kept in utf-8 encoding. The project is ported to Linux and Windows. There is a need for a to_lower functionality now. On POSIX OS I could use std::ctype_byname("ru_RU.UTF-8"). But with g++ (Debian 4.3.4-1), ctype::tolower() don't recognize Russian UTF-8 characters (latin text is lo...
If all you need is to_lower for Cyrillic characters you can write a function by yourself. АБВГДЕЖ in UTF8 D0 90 D0 91 D0 92 D0 93 D0 94 D0 95 D0 96 0A абвгдеж in UTF8 D0 B0 D0 B1 D0 B2 D0 B3 D0 B4 D0 B5 D0 B6 0A But don't forget that UTF8 is multibyte encoding. Also you can try to convert a string from UTF8 to wchar_...
1,354,224
1,354,233
Multimap output after copying from map
This program stores pairs in a map, counting the number of times a word occurs. The goal is to have the data sorted by number of occurences and output in value/string form. Obviously the normal map sorts by the string key, so I had to reverse it. To do this I read in words, and increment their values appropriately in...
for (p2 = words2.begin(); p2!=words2.end(); ++p2) cout << p->first << ": " << p->second << '\n'; Shouldn't the p's in your output statement be p2's ?
1,354,360
1,354,400
FRAPS alternative: Where to look and what for?
later this year I'm going to have a lot of time on my hands, and I thought I'd start a "small" project for myself and release it as open source. I'd like to code my own Fraps alternative. (or continue with Taksi http://taksi.sourceforge.net ). Fraps is a video & sound recording programm, which captures the screen durin...
Here is some good info on the techniques used by FRAPS. http://www.woodmann.com/forum/archive/index.php/t-11023.htm
1,354,522
1,354,534
Simple C++ Error: "... undeclared (first use this function)"
I am working on my first C++ program for school. For some reason I am getting the following error when I try to compile it: `truncate' undeclared (first use this function) Full Source: #include <iostream> #include <math.h> using namespace std; #define CENTIMETERS_IN_INCH 2.54 #define POUNDS_IN_KILOGRAM 2.2 int main...
You need forward declaration before your main: double truncate(double d); double round(double d); You could just define your functions before main, that will solve the problem too: #include <iostream> #include <math.h> using namespace std; #define CENTIMETERS_IN_INCH 2.54 #define POUNDS_IN_KILOGRAM 2.2 // round res...
1,354,621
1,354,668
Error: MFC projects cannot define _ATL_NO_EXCEPTIONS
I'm extending an open source project. After including afxcoll.h in a new C++ file in order to use CStringArray, I get this error: Error: MFC projects cannot define _ATL_NO_EXCEPTIONS I suspect I'll be able to fix the error by adding #defines or changing or rearranging the inclusion of headers, or, if that's not possib...
You could use CAtlArray<CString> instead of CStringArray, as this is compatible with _ATL_NO_EXCEPTIONS. The ATL collection classes are documented here. I normally prefer to use C++ standard library classes such as std::vector instead of the MFC container classes, though. I'd suggest investigating why _ATL_NO_EXCEPTIO...
1,354,877
1,355,057
Qt -- pass events to multiple objects?
I basically have 3 layers (Window > Scene > View) that each need to handle a mouseMove event without blocking the others. It seems only the youngest child is getting the event though. I was hoping I could process the event and then call event->ignore() to pass the event back up the stack, but it doesn't seem to be work...
QGraphicsView::mouseMoveEvent(event); Doesn't propagate up to the parent -- it actually propagates down to the scene. Here is what's happens -- QGraphicsView receives QMouseEvent, translates it into QGraphicsSceneMouseEvent and passes it to the scene. Scene then passes it to appropriate item or, in your case, prints "...
1,354,900
1,354,989
Resizing a char[] at run time
I need to resize a char array[size] to char array[new_size] at runtime. How can I do this?
ok, thanks for all the answers, I fixed my problem just by creating a new space for the new char array throwght a pointer... thanks
1,354,958
1,354,963
Memory leaks in C++ (via new+delete)
In order for an application to have no memory leaks, does the number of new in a C++ project match the number of delete?
If you mean do you need the same number of instances of delete in your source code as you have instances of new, then no. You can have objects newed in multiple places, but all these objects deleted by the same line of code. In fact this is a common idiom. Smart pointers, of varying types, generally take many different...
1,354,985
1,355,001
VS C++ program only works when .exe is run from folder? [not VS debug]
Output from debug: File opened... File contents: Output from .exe (run via double click from /project/debug): File opened... File contents: line1 line2 etc. . . Source code: #include <iostream> #include <fstream> #include <regex> #include <string> #include <list> using namespace std; using nam...
The way you've coded this line: ifstream myFile("test_data.txt"); means that the code is looking for the file in the current working directory. When you run outside the debugger that will be /project/debug (in your case), which is where the file presumably is. When you run inside the debugger that will (probably) be \...
1,355,167
1,355,256
Reading to end of file with istream_iterator and istream overload
I'm having some trouble reading data from a file into a vector of Orders. Code: #include <string> #include <vector> #include <fstream> #include <iostream> #include <iterator> using namespace std; class Purchase; class Order { public: string name; string address; vector<Purchase> items; }; class Purchas...
Regarding question #3, you could use a multimap instead of a vector. First, assume you split your Order class up as follows: class Customer{ public: string name; string address; }; class Purchase { public: string product_name; double unit_price; int count; Purchase() {} Purchase(string pn, ...
1,355,187
1,357,350
python object to native c++ pointer
Im toying around with the idea to use python as an embedded scripting language for a project im working on and have got most things working. However i cant seem to be able to convert a python extended object back into a native c++ pointer. So this is my class: class CGEGameModeBase { public: virtual void FunctionCa...
Thanks to Stefan from the python c++ mailling list, i was missing super(Alpha, self).__init__() from the constructor call meaning it never made the parent class. Thought this would of been automatic :D Only other issue i had was saving the new class instance as a global var otherwise it got cleaned up as it went out ...
1,355,342
1,355,382
C++ creating and collecting structs in a loop
I want to create a struct from data harvested by line from a file. Each line necessitates a new struct, and the lines are accessed in a while loop. In C# I did this by creating anonymous structs and adding them to a list of structs. C++ would seem not to allow anonymous structs. I tried naming them with an incrementing...
Your C++ looks to be on the right track, aside from two things. One, you have to define the form of a CollectedData struct somewhere, and two you have to give a name to your struct variable: For example, if you define the CollectedData struct like so struct CollectedData { int field1; std::string field2; bool fie...
1,355,446
1,355,932
Get visible rectangle of QGraphicsView?
I've been pulling my hair out with this one for hours. There's a thread here about it, but nothing seems to be working. QGraphicsView::rect() will return the width and height, but the left and top values aren't set properly (always 0 -- ignoring the scrolled amount). I want it in scene coordinates, but it should be eas...
Nevermind. Came up with this, which seems to work. QRectF EditorView::visibleRect() { QPointF tl(horizontalScrollBar()->value(), verticalScrollBar()->value()); QPointF br = tl + viewport()->rect().bottomRight(); QMatrix mat = matrix().inverted(); return mat.mapRect(QRectF(tl,br)); }
1,355,531
1,355,539
C++ How to loop through a list of structs and access their properties
I know I can loop through a list of strings like this: list<string>::iterator Iterator; for(Iterator = AllData.begin(); Iterator != AllData.end(); Iterator++) { cout << "\t" + *Iterator + "\n"; } but how can I do something like this? list<CollectedData>::iterator Iterator; for(Iterator = AllData.begin(); ...
It's as easy as Iterator->property. Your first attempt is almost correct, it just needs some parentheses due to operator precedence: (*Iterator).property In order to use for_each, you would have to lift the cout statments into a function or functor like so: void printData(AllDataType &data) { cout << "\t" + data.p...
1,355,564
1,355,585
Smiley face when assigning improper value type to struct property!
I am somewhat wondering if I am losing my mind, but I swear to you, this code outputs smiley faces as the .name values!! what in the world is going on? Thus far it seems to only work when the value is 1, anything else properly gives errors. I realize the code is flawed -> I do not need help with this. #include <iostrea...
The smiling face is the character with ASCII value 1. Not sure why, but apparently your compiler decided to treat it as a char, so you get the smiley.
1,355,803
1,355,862
Why is the C++ syntax so complicated?
I'm a novice at programming although I've been teaching myself Python for about a year and I studied C# some time ago. This month I started C++ programming courses at my university and I just have to ask; "why is the C++ code so complicated?" Writing "Hello world." in Python is as simple as "print 'Hello world.'" but i...
C++ is a more low-level language that executes without the context of an interpreter. As such, it has many different design choices than does Python, because C++ has no environment which it can rely on to manage information like types and memory. C++ can be used to write an operating system kernel where there is no cod...
1,355,877
1,356,128
How to pass 2D map as a parameter to a function in c++?
I have a map like std::map< int, int> random[50]; How can i pass this map as a parameter to a function say Perform()? Thanks in advance.
void Perform( std::map< int, int > r[], size_t numElements ); or void Perform( std::map< int, int >* r, size_t numElements ); Then, either way, call Perform( random, 50 ); Edit: this can also be called as follows for any const array size. Perform( random, sizeof( random ) / sizeof ( random[0] ) );
1,356,204
1,356,219
private typedef visible in derived class
I have a small problem with my compiler (VC++ 6.0). In my opinion, such a code should cause error; class Base { private: typedef int T; }; class Derived : private Base // Here the Base class can be inherited publicly as well. It does not play any role { public: T z; }; int main() { Deriv...
This behavior is a non conformance in VC++6.0, you should have got an error when defining Derived::z. (Excepted if you have business reasons to use it, there are other choices technically preferable to VC++6.0 which is old).
1,356,210
1,356,930
How to design a C++ class?
I wrote a application in MFC with C++. I need to write a class which can save all the data loaded from the database, These data might contain every kind of data type, such as int, string, byte, boolean, datetime and so on. We might filter, exchange columns, or sort on these data. For example: int int string bool dou...
I am wondering if you are emulating the DB behavior, then does it make sense to store the data in containers of 'type'? Since the data will be accessed via column-names, you need to have containers that store data-values for each column and have column-name to column-type mapping. Anyway if you want to store data along...
1,356,510
1,384,801
Relational databases application
When developing an application which mostly interacts with a database, what is a good way to start? The application requires a lot of filtering based on user input, sorting and structuring.
The best way to start is by figuring out "user stories" (or "use cases" -- but the "story" approach tends to really work great and start dragging shareholder into the shared storytelling...!-); on top of that, designing the database schema as the best-normalized idea you can find to satisfy all data layer needs of the ...
1,356,896
1,360,175
How to hide a string in binary code?
Sometimes, it is useful to hide a string from a binary (executable) file. For example, it makes sense to hide encryption keys from binaries. When I say “hide”, I mean making strings harder to find in the compiled binary. For example, this code: const char* encryptionKey = "My strong encryption key"; // Using the key a...
I'm sorry for long answer. Your answers are absolutely correct, but the question was how to hide string and do it nicely. I did it in such way: #include "HideString.h" DEFINE_HIDDEN_STRING(EncryptionKey, 0x7f, ('M')('y')(' ')('s')('t')('r')('o')('n')('g')(' ')('e')('n')('c')('r')('y')('p')('t')('i')('o')('n')(' ')...
1,357,374
1,357,406
locale-dependent ordering for std::string
I am trying to compare std::strings in a locale-dependent manner. For ordinary C-style strings, I've found strcoll, which does exactly what I want, after doing std::setlocale #include <iostream> #include <locale> #include <cstring> bool cmp(const char* a, const char* b) { return strcoll(a, b) < 0; } int main() { ...
operator() of std::locale is just what you are searching. To get the current global locale, just use the default constructor.
1,357,569
1,372,310
Using Crypto++ generated RSA keys on OpenSSL
Is there a way to use the RSA keys I've generated with the Crypto++ API in OpenSSL? What I am looking for is a way to store the keys in a format that both Crypto++ and OpenSSL can easily open them. I'm writing a licensing scheme and would want to verify signatures and decrypt files using the Crypto++ API, but to genera...
Both Crypto++ and OpenSSL can handle PKCS#8 encoded keys. In crypto++, you can generate keys and convert to PKCS#8 buffer like this, AutoSeededRandomPool rng; RSAES_OAEP_SHA_Decryptor priv(rng, 2048); string der; StringSink der_sink(der); priv.DEREncode(der_sink); der_sink.MessageEnd(); // der.data() is the bytes you...
1,357,733
1,357,747
Best way to display output of pattern search on text files?
first question here! I'm writing a grep type program for Windows, just for fun (using Mingw). It works well for text files where lines are terminated by '\n'. I'm using fstream::getline() for this. But I also need to be able to search files containing just a giant block of text with no line numbers. fstream::getline() ...
istream::read() will read an arbitrary number of characters from an istream. As for where in the file it was found, a line number and character offset might be a good way to go.
1,357,807
1,357,937
when is better to use c++ template?
right now i am learning C++, and now I know the basic concept of template, which act just like a generic type, and i found almost every c++ program used template, So i really want to know when are we supposed to use template ? Can someone conclude your experience for me about c++ template ? When will you consider to...
Re: supplement. If you want to pass a comparison function, you could provide another overload: template <class myType> const myType& GetMax (const myType& a, const myType& b) { return (a<b?b:a); } template <class myType, class Compare> const myType& GetMax (const myType& a, const myType& b, Compare compare) { ...
1,357,982
1,358,124
gvim :make command does not work
I am under a Unix environment, working in C++. I'm opening gvim from a directory in which a makefile called "Makefile" exists. When I try to use ":make" from within vim, I get: shell returned 2 (1 of 1): make: *** No targets specified and no makefile found. Stop.
Can you check the following options? :set shell? :set shelltype? Finally, check the contents of your shell login file. For example, if your shell is bash, check ~/.bashrc. Does this file contain something like the following? cd ~ Or: cd /home/${USERNAME} where ${USERNAME} is (obviously) your username.
1,358,400
1,358,622
What is external linkage and internal linkage?
I want to understand the external linkage and internal linkage and their difference. I also want to know the meaning of const variables internally link by default unless otherwise declared as extern.
When you write an implementation file (.cpp, .cxx, etc) your compiler generates a translation unit. This is the source file from your implementation plus all the headers you #included in it. Internal linkage refers to everything only in scope of a translation unit. External linkage refers to things that exist beyond a...
1,358,427
1,358,443
Function which returns an unknown type
class Test { public: SOMETHING DoIt(int a) { float FLOAT = 1.2; int INT = 2; char CHAR = 'a'; switch(a) { case 1: return INT; case 2: return FLOAT; case 3: return CHAR; } } }; int main(int argc, char* argv[]) { Test obj; cout<<obj.DoIt(1); return 0; } Now, using the knowledge that ...
You can use boost::any or boost::variant to do what you want. I recommend boost::variant because you know the collection of types you want to return. This is a very simple example, though you can do much more with variant. Check the reference for more examples :) #include "boost/variant.hpp" #include <iostream> typed...
1,358,508
1,358,616
referencing a function's arguments by position?
I'm not sure I know how to ask this. say I have a function void myFunc ( int8 foo, float bar, int whatever ) { ... } is there a quick way of referencing a particular argument by its position? void myFunc ( float foo, float bar, float whatever ) { float f; f = ARG[1]; // f now equals bar } something to that effe...
If it really seems like what you need is a parameter array of values of the same type instead of explicitly named parameters, then you can just pass an array as a parameter. void myFunc ( float foo[3] ) { float bar; bar = foo[1]; } That can be inefficient if your array is much longer, so a better solution woul...
1,358,748
1,359,073
Visual Studio 2008 Profiler - Instrumented produces strange results
I run the Visual Studio 2008 profiler on a "RelDebug" build of my app. Optimizations are on, but inlining is only moderate, stack frames are present, and symbols are emitted. In other words, RelDebug is a somewhat optimized build that can be debugged (although the usual Release caveats about inspecting variables applie...
You say "of course you are looking at Exclusive". Look at inclusive stats. In all but the simplest programs or algorithms, nearly all the time is spent in subroutines and functions, so if you've got a performance problem, it most likely consists of calls you didn't know were time-hogs. The method I rely on is this. Ass...
1,359,003
1,360,394
svg example in C/C++
Can someone provide an example of how to load a .svg file and display it using C/C++ and any library? I'm wondering if you will use SDL, cairo, or what.
As Pavel put it, QtSvg is the way to go i believe. It is easier to use but in our team we have faced performance issues with QtSvg especially on Linux. So we decided to directly parse the SVG file XML by hand and render it using Qt itself. This turned out to be much faster. pseudocode:- // Read the SVG file using XML p...
1,359,172
1,359,212
VS2008 C++ Compiler error?
this compiles :-) string name; name = 1; this does not: string name = 1; any thoughts? I know that this is wrong. . . that is not the point. The first gives a smiley face.
The first compiles because the assignment operator is called what has one signature of "string& operator= ( char c )" and the compiler can convert 1 into a char. The second won't compile because it calls the copy constructor which has no compatible signature.
1,359,620
1,360,028
Save bitmap to video (libavcodec ffmpeg)
I'd like to convert a HBitmap to a video stream using libavcodec. I get my HBitmap using: HBITMAP hCaptureBitmap =CreateCompatibleBitmap(hDesktopDC, nScreenWidth, nScreenHeight); SelectObject(hCaptureDC,hCaptureBitmap); BitBlt(hCaptureDC,0,0,nScreenWidth,nScreenHeight,hDesktopDC,0,0,SRCCOPY); And I'd like to convert...
I am not familiar with the stuff you are using to get the bitmap, but assuming it is correct and you have a pointer to the BGR 32-bit/pixel data, try something like this: uint8_t* inbuffer; int in_width, in_height, out_width, out_height; //here, make sure inbuffer points to the input BGR32 data, //and the input and o...
1,359,703
1,359,759
custom data iostream
I have a data structure defined as struct myDataStruct { int32_t header; int16_t data[8]; } and I want to take a character stream and turn it into a myData stream. What stream class should I extend? I would like to create a custom stream class so that I can do things like myDataStruct myData; myDataStruct myDa...
Instead of myDataStream.get(myData), what you do is overload operator>> for your data type: std::istream& operator>>(std::istream& is, myDataStruct& obj) { // read from is into obj return is; } If you want to read into an array, just write a loop: for( std::size_t idx=0; idx<10; ++idx ) { myDataStruct tmp; ...
1,359,903
1,736,663
free non-gpl data compression libraries
i'm writing project that stores data, so i need to compress it. I've tried zlib but it's bottleneck of my project. So maybe there is faster solution. I don't need a great compress ratio, but i'm looking for really fast compression. Are there any other data compression libraries except zlib, that are really free and can...
Here are a few: FastLZ -- fast and lightweight, MIT license unless you want to use it under a GPL license LZJB -- also fast and pretty lightweight, used as default compression algorithm for Sun's ZFS
1,360,163
1,360,179
Problem with file loop and reading into map
The while loop I have while reading in from a file doesn't break. I'm not sure what the problem is. If you need any more information just ask. Code: #include <string> #include <map> #include <fstream> #include <iostream> #include <iterator> using namespace std; class Customer { public: string name; string add...
As for your Customer/Purchase ostream inserters, declare the second argument const& instead of non-const &. For example: ostream& operator<<(ostream& out, Customer const& c) That's necessary because the key in a map is immutable even if you're using a non-const iterator (modifying the key would invalidate whatever tr...
1,360,257
1,360,282
Should I attempt to fix an arguably poor design decision in a 3rd party library?
My project involves Qt plus and unnamed 3rd party physics simulation library. The way the physics library works is that physical bodies cannot create themsleves; the "world" must instantiate them so that they can be added to the world immediately. My project creates a wrapper around these physical bodies to add some ex...
To be truely effective, a facade pattern (your wrapper) has to hide the underlying details of the implementation from the user of the facade. This does mean using data transfer objects to hold the data. Facades can be cumbersome to implement but they give you the ability to change out the underlying implementation with...
1,360,673
1,362,307
Any valid reason for code duplication?
I'm currently reviewing a very old C++ project and see lots of code duplication there. For example, there is a class with 5 MFC message handlers each holding 10 identical lines of code. Or there is a 5-line snippet for a very specific string transformation every here and there. Reducing code duplication is not a proble...
When I first started programming, I wrote an app where I had a bunch of similar functionality which I wrapped up in a neat little 20-30 line function ... I was very proud of myself for writing such an elegant piece of code. Shortly after, the client changed the process in very specific cases, then again, then again, ...
1,360,880
1,360,916
Best way to explain declarative fallacy in C++?
How might one craft a good explanation of why the following code is not correct, in that the author is attempting to write C++ code declaratively rather than procedurally? const double NEWTONS_PER_POUND = 4.448; int main() { double pounds, newtons; pounds = newtons/NEWTONS_PER_POUND; /* pounds equals 'unassigned...
Tell the author that pounds = newtons/NEWTONS_PER_POUND; commands the CPU to take the value at the address referred to as "newtons" take the value at the address referred to as "NEWTONS_PER_POUND" divide them store the result at the address referred to as "pounds" what he is looking for is most probably a function i...
1,360,974
1,367,004
ImpersonateLoggedOnUser and starting a new process that uses ocx fails
I write a c++ windows application (A), that uses LogonUser, LoadUserProfile and ImpersonateLoggedOnUser to gain the rights of another user (Y). Meaning the A starts using the user that is logged on on the workstation (X). If the user wants to elevate his rights he can just press a button and logon as another user witho...
Thank you all for your help. The following was able to solve the issue for me: I start the desired process using CreateProcessWithLogonW(). To get that function working properly I have to RevertToSelf() before I call it and do the impersonation again afterwards. So the sequence is now: LogonUser() LoadUserProfile() ...
1,361,028
1,361,575
stop python object going out of scope in c++
Is there a way to transfer a new class instance (python class that inherits c++ class) into c++ with out having to hold on to the object return and just treat it as a c++ pointer. For example: C++ object pyInstance = GetLocalDict()["makeNewGamePlay"](); CGEPYGameMode* m_pGameMode = extract< CGEPYGameMode* >( pyInstance...
You must increment the reference count of the pyInstance. That will prevent Python from deleting it. When you are ready to delete it, you can simply decrement the reference count and Python will clean it up for you.
1,361,071
1,361,074
What is the difference between .LIB and .OBJ files? (Visual Studio C++)
I know .OBJ is the result of compiling a unit of compilation and .LIB is a static library that can be created from several .OBJ, but this difference seems to be only in the number of units of compilation. Is there any other difference? Is it the same or different file format? I have come to this question when wondering...
A .LIB file is a collection of .OBJ files concatenated together with an index. There should be no difference in how the linker treats either.
1,361,229
1,361,282
Using a static library in Qt Creator
I'm having a hell of a time finding documentation which clearly explains how to use a static library in Qt Creator. I've created and compiled my static library using Qt Creator (New=>Projects\C++ Library=>Set type to "Statically Linked Library"). It compiles and spits out a ".a file". The problem I encounter is when I ...
LIBS += -L[path to lib] -l[name of lib] Note! that filename of lib: lib[nameOfLib].a and you have to pass only original part -l[nameOfLib]
1,361,310
1,361,345
Converting unmanaged C++ code to C#
Anyone with pointers to a tool/utility for converting unmanaged c++ to c#? I have tried the http://www.pinvoke.net/ site but I cant find reference to this API AddUsersToEncryptedFile on this question.
In general this is really hard, because C++ offer different features than C#: templates, friends, zero-terminated strings, unmanaged pointers, COM, etc., not to mention that parsing C++ is a bitch of a job. To do it, you need a full C++ parser with name and type resolution, a set of ideas about how to convert each cons...
1,361,432
1,361,443
Compliation Error of a C++ second life library
I am trying to compile a slight part of second life library. Specifically, it is the llcommon part. I compiled it in Windows System with VS9. I failed and the compiler said it cannot recognize '_Ios_Openmode' as a member of 'std' The corresponding code is as following: explicit llifstream(const std::string& _Filename, ...
I think it's meant to be std::ios::openmode.
1,361,618
1,361,837
Const Overloading: Public-Private Lookup in C++ Class
The following code does not compile, saying " error C2248: 'A::getMe' : cannot access private member declared in class 'A'". Why? I am trying to call the public interface. class B { }; class A { public: const B& getMe() const; private: B& getMe(); }; int main() { A a; const B& b = a.getMe(); return 0; }
Part of the problem which wasn't mentioned in other answers is that accessibility and visibility are independent concepts in C++. The B& A::getMe() private member is visible in main even if it isn't accessible. So in your call a.getMe() there are two overloaded members to consider, B& A::getMe() and B const& A::getMe...
1,361,965
1,362,005
Compile simple string
Was just wondering if there are any built in functions in c++ OR c# that lets you use the compiler at runtime? Like for example if i want to translate: !print "hello world"; into: MessageBox.Show("hello world"); and then generate an exe which will then be able to display the above message? I've seen sample project ar...
It is possible using C#. Have a look at this Sample Project from the CodeProject. Code Extract private Assembly BuildAssembly(string code) { Microsoft.CSharp.CSharpCodeProvider provider = new CSharpCodeProvider(); ICodeCompiler compiler = provider.CreateCompiler(); CompilerParameters compilerparams = new ...
1,362,063
1,362,151
naming convention of temp local variables
What is the standard way to name a temp variable in the local function? let me give you an illustration of what I am doing. I get a pointer to a structure, so I want store one of its members locally to avoid a de-referenced, and then any modification assign back to the pointer. To be more concrete: struct Foo { dou...
Linus Torvalds - Linux Kernel coding style from Linus Torvalds : LOCAL variable names should be short, and to the point. If you have some random integer loop counter, it should probably be called "i". Calling it "loop_counter" is non-productive, if there is no chance of it being mis-understood. Similarly, "tm...
1,362,154
1,362,183
Registering class instances for to be controlled by a class's function
Hehe I'm having hard time on choosing the question title. But let me explain about my problem to make it clearer. I'm now writing my own GUI library for my game in C++ with a DirectX wrapper out there. But I got no idea on how to render my in-game windows by just calling the "manager" class's draw function. For example...
Yes basically that will work, why don't you just try it out? But I would prefer using iterators instead of your loop, and also some kind of auto-pointer instead of just new (current example will probably cause a memory leak). Actually, begin by Googling std::vector... And passing arguments as references.
1,362,328
1,362,366
What is the mechanism through which destructors are called for stack-assigned objects?
How does C++ ensure that destructors are called for stack assigned objects? What happens to the destructor function (or a pointer to it) when I assign dynamic memory as follows: class MyClass { public: ~MyClass() { std::cout<<"Destructor called."<<std::endl; } MyClass() { std::cout<<"Constructor c...
The compiler inserts a call to the destructor for the object at an appropriate position.
1,362,674
1,650,158
Problem synchronizing QThreads
Apart from main thread, I've ThinkerThread object _thinker whose finished() signal is connected to main thread's slot: connect(&_thinker, SIGNAL(finished()), this, SLOT(autoMove())); The slot autoMove() causes _thinker to initialize and run again: _thinker.setState(/* set internal variables to run properly */); _think...
How about using an integer id to determine which state has been computed, to see if it's still valid when computation has finished?
1,362,689
1,426,385
reducing memory requirements for adjacency list
I'm using adjacency_list< vecS, vecS, bidirectionalS ... > extensively. I have so many graphs loaded at once that memory becomes an issue. I'm doing static program analysis and store the callgraph and flowgraphs of the disassembled binary in boost graphs. Thus I can have several ten thousand functions==flowgraphs and o...
There is a little known graph type called "compressed sparse row" graph in the BGL. It seems to be quite new and is not linked from the index pages. It does however employ a beautiful little trick to get the graph representation as small as possible. http://www.boost.org/doc/libs/1_40_0/libs/graph/doc/compressed_spars...
1,362,728
1,363,656
C Runtime Library Version Compatibility: updates require rebuilds?
How do you construct a library (static lib or a dll/so) so that it isn't sensitive to future updates to the system's C runtime librarires? At the end of July, Microsoft updated a bunch of libraries, including the C runtime libraries. Our app is written with a mix of MFC/C++/VB and some third party libraries, including ...
If you are loading the 3rd party libraries as DLLs, they may depend on different runtime versions than your executable as long as you are not handing over parameters of types, that depend on the runtime libs (like STL types) the 3rd party lib is able to load the version of the runtime, that it has been built with or i...
1,363,147
1,363,214
Is a public constructor in an abstract class a codesmell?
Is a public constructor in an abstract class a codesmell? Making the constructor protected provides all of the access of which you could make any use. The only additional access that making it public would provide would be to allow instances of the class to be declared as variables in scopes that cannot access its prot...
My opinion would be that the public constructor might be seen to be confusing, and as you say making it protected would be correct. I would say that a protected constructor correctly reinforces the impression that the only sensible use of an abstract class is to derive from it. In fact, you only need to declare a cons...
1,363,217
1,363,359
Binary Reproducibility in Visual C++
Is there a way to force the same code to produce the same binary in Visual C++? Turn off the timestamp in the PE or force the timestamp in the PE to be some fixed value, in other words?
I suppose you could write a utility to open the PE, set the checksum to 0, set the timestamp to what you like, recompute the crc, then write it back out. It would be nice if there were an official way to ensure perfect binary reproducibility, though. For more information: http://msdn.microsoft.com/en-us/magazine/cc301...
1,363,411
1,363,457
What to learn first - C++/STL/QT or .NET/C# - if I have limited time while learning and working?
I am currently a CS student at a 4th year(of total 5). I`m studying and working. At work I use ASP.NET. So, while working and studying, I have not so much time to learn new languages and techniques. What do you suggest to learn first - C++/STL/QT or C#/LINQ/WPF? I mean, C++ and its libraries are stable and do not chang...
C++ is the cadillac of tools. Harder to learn and use but more powerful. C# does a lot of hand holding and is easier to learn but more limiting. Do you want to be the best of the best? Choose C++. Do you just want a job? Choose C#
1,363,665
1,363,687
Visual C++ math.h bug
I was debugging my project and could not find a bug. Finally I located it. Look at the code. You think everything is OK, and result will be "OK! OK! OK!", don't you? Now compile it with VC (i've tried vs2005 and vs2008). #include <math.h> #include <stdio.h> int main () { for ( double x = 90100.0; x<90120.0; x+=1 ...
Could be this: http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.18 I know it's hard to accept, but floating point arithmetic simply does not work like most people expect. Worse, some of the differences are dependent on the details of your particular computer's floating point hardware and/or the optimization se...
1,363,787
1,365,438
Is it safe to call CFRunLoopStop from another thread?
The Mac build of my (mainly POSIX) application spawns a child thread that calls CFRunLoopRun() to do an event loop (to get network configuration change events from MacOS). When it's time to pack things up and go away, the main thread calls CFRunLoopStop() on the child thread's run-loop, at which point CFRunLoopRun() re...
In particular, is calling CFRunLoopStop() from another thread [safe]? Here's what Run Loop Management says: The functions in Core Foundation are generally thread-safe and can be called from any thread. So maybe CFRunLoopStop is safe. But I do worry about their use of the word “generally”. My rule is: If Apple doesn...
1,363,990
1,364,004
Help with semi-complex C++ assignment
This is a really easy question I'm sure but I'd appreciate the help. :) Here's my variable in the .h file: map<int, map<int, map<int, CString>*>*> batch; Here's me trying to assign a value: ((*((*(batch[atoi(transnum)]))[1]))[atoi(*docnum)]) = page; I added some extra parentheses while trying to figure this out in or...
The way std::map works is that it will allocate a node you are trying to reference if it does not exist yet. That means unless you are allocating your submap(s) and inserting them into your supermap(s), you're going to be given pointers to memory you don't own. At that point when you try to write to that memory you wil...
1,364,112
1,364,189
sizeof on a class inheriting from a base class with a virtual function
For the following code fragment. /*This program demonstartes how a virtual table pointer * adds to a size of a class*/ class A{ }; class X{ public: void doNothing(){} private: char a; }; class Z:public X { public: void doNothing(){} private: char z; }; class Y{...
Here is Stroustrup's explanation of why size of an empty class cannot be zero. As to why it is 1 byte, as opposed to something that conforms to the alignment boundaries, I would guess this depends on the compiler.
1,364,144
1,364,190
Determine total number of bytes read by a process
I am currently working on a project where one of our goals is to reduce the total amount of data read from disk. Is there a way to determine the total number of bytes run by a process? I am working with on a C++ application built with Visual Studio 2005, running on Windows XP. Ideally, I would like some sort of monitor...
You can use GetProcessIOCounters function. This returns total read operations, write operations, other, read bytes, write bytes, and other bytes. The process still needs to be alive for this to work - holding a handle to the process should be sufficient. Alternatively, your process could log this info on exit. If yo...
1,364,165
1,364,277
linked list with no duplicates
I have the following code (correct for my simple tests) for a linked list for no duplicates, but I think it is a bit ugly. Could anyone recommend a cleaner way to handle the duplicate code? The current piece in question is: if( (val == cur->val) || (cur->next && (val == cur->next->val)) ) But I think that a better so...
I would write this more like: void insert(Node ** ppHead, const int val) { if (ppHead == NULL) return; while (*ppHead && (*ppHead)->val < val) ppHead = &(*ppHead)->next; if (*ppHead && (*ppHead)->val == val) return; Node * tmp = new Node(val); // new throws tmp->next = *ppHea...