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
5,989,010
5,989,097
Contradiction in C++ standard?
A std::map must satisfy the requirements of an associative container specified in paragraph 23.1.2/2: Each associative container is parameterized on Key and an ordering relation Compare that induces a strict weak ordering (25.3) on elements of Key. In addition, map and multimap associate an arbitrary type T ...
Compare is the type of the comparator. The fact that it is declared with class instead of typename doesn't make a difference, you can have a pointer to function as type and give your function in the map constructor. #include <map> bool myCmp(int a, int b) { return a < b; } void foo() { std::map<int, char*, b...
5,989,234
5,989,321
Getting a compilation error in VS2010 by following the first hello world example
i just started learning MFC..found a tutorial here http://bit.ly/j2uhHO ..just tried the same thing in VS2010 but getting a compilation error in this code.. void CChildView::OnPaint() { CPaintDC dc(this); // device context for painting dc.TextOut(0, 0, "Hello, world!"); // TODO: Add your message handler...
The error tells you whats exactly wrong. error C2664: 'BOOL CDC::TextOutW(int,int,const CString &)' : cannot convert parameter 3 from 'const char [14]' to 'const CString &' TextOutW() is expecting const CString & as the third parameter and you are passing const char [14] You need to do: dc.TextOut(0, 0, L"Hello, world...
5,989,255
6,161,662
C++ compare surf descriptors algorithm match breaks some times
I wrote a c++ application that compares points matches from images (OpenSurf C++) but some times, 1 from some thousands of "getUniqueMatches", the application breaks in some point inside "getUniqueMatches". I has this log: 05/13/11 10:17:16: this->pointsA = 227 05/13/11 10:17:16: this->pointsB = 226 05/13/11 10:17:16: ...
I suspect 2 things: g++ compiler optimization. Use -O2 or less; -O3 and beyond sometimes generate weird behavior especially concerning floating point operation. If reducing optimization does not fix the problem, I suggest changing if (d1 / d2 < ratio) to if (d1 < double(ratio)*d2) for avoiding division by zero (unli...
5,989,288
5,989,428
Some questions in STL map and list using in c++
Hello I would like to ask about: I have map and list Questions: Is the following implementation of distructor right : for (map<string,SymbolTableNode*>::iterator i = symbolTable.begin(); i != symbolTable.end(); ++i) { delete i; } symbolTable.clear(); or I miss some memory? A...
Do you really need to have a list of pointers ? Can't you have a plain list ? list<MyClass> mylist; mylist.push_front(MyClass()); It will save you the pain of memory management. If you need pointers, then use smart pointers or pointer containers from boost : http://www.boost.org/doc/libs/1_46_1/libs/ptr_container/doc/...
5,989,459
5,989,673
How to protect application written in C++ .NET
I have written an application and now I want to protect in. Application is written in C++ using .NET framework. I want to know what methods can I use in order to protect application. For example if I give application to "A", "A" must register it and only after that he can use it. And if "A" give application to "B", "B"...
You will not be able to stop a determined user from breaking your system. You need a system that would slow down a determined user and be low-friction for the average user. You need something that uniquely identifies "A" and "B", and helpfully there's the MAC address of the network card. It is possible to alter this bu...
5,989,616
5,989,774
Strange behaviour from system call creat
I am creating a file as follows int fd = creat(file_path.c_str() ,S_IRWXU|S_IRWXG|S_IRWXO); Though i am providing all permissions to all three entities, it creates the files with the below permission. -rwxr-xr-x The directory i am creating this in has permissions set as drwxrwxrwx Umask 0022 Can you guys please...
Permissions in the umask are turned off from the mode argument to open and mkdir (and creat and friends, similarly). For example, if the mode argument is specified as: S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH (0666) when creating a file with the typical umask of 0022, the result will be S_IRUSR | S_IWU...
5,989,652
5,989,744
Initializing variable in C++ function header
I've come across some C++ code that looks like this (simplified for this post): (Here's the function prototype located in someCode.hpp) void someFunction(const double & a, double & b, const double c = 0, const double * d = 0); (Here's the first line of the function body located in someCode.cpp that #include's someCode...
Yes, this is legal, this is called default arguments. I would say it's preferred to overloading due to involving less code, yes. Regarding your comment about const, that doesn't apply to the default value itself, it applies to the argument. If you have an argument of type const char* fruit = "apple", that doesn't mean ...
5,989,670
5,989,718
What is the correct way to delete char**
I have a char**, basically an array of strings, that I need to delete. What is the correct way of doing this to ensure all pointers are cleared up?
char** StringList ; int nStrings ; .... for (int i = 0 ; i < nStrings ; i++) delete[] StringList[i] ; delete[] StringList ; Of course, it's simpler if you start with std::vector<std::string> Stringlist ; Then it's just StringList.clear() ;
5,989,734
5,991,173
Effective C++ Item 23 Prefer non-member non-friend functions to member functions
While puzzling with some facts on class design, specifically whether the functions should be members or not, I looked into Effective c++ and found Item 23, namely, Prefer non-member non-friend functions to member functions. Reading that at first hand with the web browser example made some sense, however convenience fun...
Access to the book is by no mean necessary. The issues we are dealing here are Dependency and Reuse. In a well-designed software, you try to isolate items from one another so as to reduce Dependencies, because Dependencies are a hurdle to overcome when change is necessary. In a well-designed software, you apply the DRY...
5,989,753
5,989,789
How much is deleted when you delete a class or struct in c++?
This is just an idle thought I had when reading this other question: What is the correct way to delete char** If the chars mentioned in that question had been created inside an object and that object was deleted, would that correctly clean up the pointers as well, or would they be stuck in memory?
If you delete an object, the destructor for that object will be called, so you need to do a delete in the destructor. So remember, everything that the class has allocated on the heap has to be freed in the destructor. If it was been allocated on the stack this happens automatically struct A { A() { std::cout << "A(...
5,989,823
5,989,869
Polymorphism Problem C++
I have these classes: class A { }; class B : public A { public: B(int val); private: int* m_int; }; B::B(int val) { m_int = &val; } I call the code like so, inside 1 function, i know the vars will be destroyed once they are out of scope, but I only need them in this function: { ... int _int = 0; B obj(_i...
The pointer m_int will stay the same but the value pointed to *m_int will change, you'll also have to pass the value val by reference to the function. EDIT: Saw your edited question, since this is done from the constructor you can do: class B : A { public: B(int& val) : m_int(val) {} private: int& m_int; }; To...
5,989,835
5,992,214
Windows does not flush COM-Buffer
I'm seeing some pretty odd behaviour from windows regarding my COM-Buffers. I use 3 USB-Serial Converter with FTDI chips. I open the com ports with CreateFile and it all works fine. All 3 ports have the same configuration except for the baud rates. 2 work at 38400 and one at 9600. Here is the odd part: I am able to suc...
This is kind of a shot in the dark... but. Check the flow control settings for both ends of the "weird" connection. I've seen strange things like this when the flow control is mismatched. The act of closing the port clears the bits and allows the buffered data to flow.
5,989,993
5,993,524
How to get device properties in windows in c++?
In Windows, if I open Device Manager-> right click on the device -> Properties -> Details, I get {Property, Value} pairs. I want to access them in my C++ code in Visual Studio. How do I get it? Thanks,
Try SetupDi_ functions,look here for example. HDEVINFO WinDeviceHelper::getDevInfoForClass(QString devClassName,DWORD& dwCount) { //DWORD dwGuids = 0; SetupDiClassGuidsFromNameW( qPrintableW(devClassName), 0, 0, &dwCount ); //emit sSearchStarted(dwGuids); if(dwCount) { GUID* pGuids = new...
5,990,019
5,991,432
Drag-and-drop files from a Zip folder into my window
I'm trying to implement a feature when contents of a Zip archive could be dragged-and-dropped from a Windows Explorer's Zip folder into my window. I implemented all necessary methods of IDropTarget and everything works fine when I drag-n-drop regular files from the Windows Explorer. The issue happens in the following m...
I can't imagine Explorer's zip file handler implements CF_HDROP as that would require it to extract the files before initiating the drag. I am betting it uses CFSTR_FILEDESCRIPTOR and CFSTR_FILECONTENTS.
5,990,094
5,990,249
Isolated a segfault - but why is it happening?
Using the DevC++ debugger (still new to it), I'm pretty sure I've isolated a segfault scenario, but I've got no idea why it's happening. void LinkedList::Add(const char *Word){ ListNode *newNode = new ListNode; strcpy(newNode->Word, Word); newNode->Next = NULL; ... } A segfault occurs at the "newNode->...
You have not allocated any memory for Word pointer in the ListNode structure. Without this, it is pointing to some random location and whenever you are trying to write to that location (using strcpy) you will get an access violation. The simplest way to solve this is to use the std::string class and get rid of all manu...
5,990,551
5,990,612
Template class: No default constructor
I know there are a million posts about this, but I still can't figure out why this isn't working =/ this line: test = new Test2<Test>; gives me this error: error C2512: 'Test2<PARENT>' : no appropriate default constructor available with [ PARENT=Test ] code: template<class PARENT> class Test2; //////////////////...
At the point of instantiation (i.e. inside the Test constructor), all the compiler has so far is a forward declaration of Test2<>; it doesn't yet know what constructors are available. To solve, either move the definition of Test2<> before that of Test, or move the definition of the Test constructor outside the class de...
5,990,576
5,990,785
static_cast with bounded types
When you cast an int in short with a classic static_cast (or c cast), if the value is out of the short limits, the compiler will truncat the int. For example: int i = 70000; short s = static_cast<short>(i); std::cout << "s=" << s << std::endl; Will display: s=4464 I need a "inteligent" cast able to use the type limit...
Take a look at boost's Numeric Conversion library. I think you'll need to define an overflow policy that truncates the source value to the target's legal range (but I haven't tried it). In all, it may take more code than your example above, but should be more robust if your requirements change.
5,990,708
7,242,616
Qt telephony always dialing the same number
We have an app that uses qt mobile extensions, more specifically XQTelephony. The app uses it to call numbers like "123p5". What happens is that the app dials "123" and then post-dials "p5" which is what we want. The problem is that if I dial a number like "123p5" and then I try to dial again for example "123p2" or wha...
After some time. I finally found a possible solution, though not great :-). The solution is not to use the extensions, but instead use the integrated browser. If you give it a url in the form "123pp1231" it will work. However, there is a small bug. Once a browser is open. This want work any more. So once you do one cal...
5,990,825
5,990,913
Convert an ASCII std::string to hex
is there an easy way to convert an ASCII std::string to HEX? I don't want to convert it to a number, I only want to convert each ASCII character to it's HEX value. The output format should also be a std::string. i.e.: "TEST" would be "0x54 0x45 0x53 0x54" or some similar format. I found this solution, but maybe there i...
If you don't care about the 0x it's easy to do using std::copy: #include <algorithm> #include <sstream> #include <iostream> #include <iterator> #include <iomanip> namespace { const std::string test="hello world"; } int main() { std::ostringstream result; result << std::setw(2) << std::setfill('0') << std::he...
5,990,882
5,997,155
Double-Array Trie Question
I am trying to understand Double-Array Trie implementation from http://linux.thai.net/~thep/datrie/datrie.html But I do not understand following part. check[base[s] + c] = s base[s] + c = t What does adding c means here. Can anybody explain algorithm in simple language.
Imagine you collaps a 2D array into a 1D array: int arr2D[2][3]; int arr1D[2 * 3]; // # of rows * # of columns // access element [1][2] of 2D array, i.e., the last element int elem2D = arr2D[1][2]; // access element [1][2] of 1D array, i.e., the last element int elem1D = arr1D[1 * 3 + 2]; // ==========================...
5,990,898
5,992,834
How to overload the ostream operator << to make it work with log4cxx in C++?
Say I have a class A and an operator<< declared like so: // A.h class A { // A stuff }; std::ostream& operator<<(std::ostream& os, const A& a); somewhere else I use my logger with A: LoggerPtr logger(LogManager::getLogger("ThisObject")); A a; LOG4CXX_INFO(logger, "A: " << a); The compiler is complaining: binary '...
You could try declaring your operator << in namespace std (that's legal, since you're passing an instance of your user-defined type): namespace std { ostream& operator<<(ostream& os, const A& a); }
5,990,919
5,990,939
Insert pair as map value
typedef pair<unsigned char, unsigned char> pair_k; map<unsigned char, pair_k> mapping; Which will be used this way: mapping[100] = make_pair(10,10); Question is: Is this allowed? Syntaxically, it feels alright. Would this be access as an array as oppose to a map?
That looks ok to me. But note that this is not array access; it just looks like it because std::map overloads operator[]. If you do mapping.size() afterwards, you will find that it will be 1.
5,990,982
5,991,033
Identify objects in boost::shared_ptr<boost::thread>
I am building an application based on an example on the boost website. These are the relevant definitions to know of: typedef boost::shared_ptr&lt connection &gt connection_ptr; std::set&lt connection_ptr&gt connections_; std::vector&lt boost::shared_ptr&lt boost::thread&gt &gt threads; where connection is a class. I...
If you use a map (or other associative container) instead of vector you can maintain an association between connections and threads: std::map<connection_ptr, boost::shared_ptr<boost::thread> > threads; allows you to write: threads[connection] = thread; instead of the push_back call after you create the thread and the...
5,990,998
5,991,027
Returning stl containers from functions
What is the best way (performance-wise) of returning stl containers from a function? The container returned would usually contain several thousands of items. Method 1: typedef std::list<Item> ItemContainer; ItemContainer CreateManyItems() { ItemContainer result; // fill the 'result' ... return result; }...
None: if you just want to fill std::list with items, then you can use std::fill or std::fill_n or a combination of standard library functions. It's not clear how exactly you want to fill your list, so I can't comment on your code precisely. If possible, use the standard library. If you cannot, then go for Method 1, and...
5,991,067
5,991,106
C++ Safe Exception Handling
Let's have a piece of code (fstream is just an example, we could be talking about dynamic memory allocation...): fstream f; try { f.open("xxx"); ... f.close(); } catch (...) { ... } When something goes wrong I would like to close() the file (release memory or whatever), but I don't know the state of f. After ...
fstream destructors call close for you. When an exception is thrown, the file is closed automatically. For managing memory, you can use smart pointers. For managing mutexes or more general locks, most libraries provide you with a class whose destructor unlocks the mutex for you. Never write code in the form: acquire a ...
5,991,207
5,991,352
How can I get set input files path runtime?
I need to select the path directory of my "files.dat" at runtime. My Visual Studio project create a .dll (that is a Nutech plugin) and in the code it is just implemented a load functions of this files. So I need that the user can choose the directory of files to load to the process.
Your function must receive a name of an input file as a parameter and do exactly one thing: load data from the file. Everything else (like showing a dialog) is responsibility of the user code.
5,991,277
5,991,331
A question about function call and evaluation in C++
Hey there, I have a probably straight-forward question about the following problem: I have a function double afunction(double *myarray) { double ret = 1.0; for(int i = 0; i < 4; i++) ret *= myarray[i]*myarray[i]; return ret; } Now I want to modify it so that I pass two new parameters: int index ...
double afunction(double *myarray, int index, double *add) { double ret = (*add) * (*add); for(int i = 0; i < 4; i++) if( i != index ) ret *= myarray[i]*myarray[i]; return ret; }
5,991,306
5,991,509
Remote host doesn't compile but it should
I am using Netbeans and I am using a remote machine as Development host. If this last is set to localhost everything builds fine, BUT when I move to the remote machine I have the error below ( it is really as it is outputted ). The only difference is that my local is not 64 bit while the other one it is. If I build th...
You are using relative paths to link, and the linking fails (not compilation). Either copy the libraries to correct path, or fix your makefile.
5,991,415
5,993,357
C++/MFC How to copy multiple files from PC to WinCE (Mobile Device)?
I am trying to copy entire directory including all the files and subdirectories inside from PC into WinCE (Mobile Device). I am aware of the RAPI.DLL to control files within WinCE, but I doesn't seem to work between PC and WinCE. Neither the Win32 file control interface. It would be appreciated if someone helps me to s...
To copy file to a device you have a few options: Use RAPI. This requires that ActiveSync is part of the CE OS and you have an active ActiveSync/WMDC connection to the device. Use a server on the device like FTP. This requires that the server is in the OS, enabled and configured. Use a network share to copy to the de...
5,991,507
5,991,671
Template partial specialization for __stdcall function pointer
typedef bool (*my_function_f)(int, double); typedef bool (__stdcall *my_function_f2)(int, double); // ^^^^^^^^^ template<class F> class TFunction; template<class R, class T0, class T1> class TFunction<R(*)(T0,T1)> { typedef R (*func_type)(T0,T1); }; int main() { TFunction<my_function_f> t1; // works ...
No, this is by design. The calling convention is very much part of the function declaration, your template function uses the default calling convention. Which is not __stdcall unless you compile with /Gz. The default is /Gd, __cdecl. The code compiles when you target x64 because it blissfully has only one calling co...
5,991,809
5,991,937
General question: What to pass as pointer in C/C++?
Hey there, I wonder if it's worth passing primitive single values like int, float, double or char by pointer? Probably it's not worth!? But if you would simply pass everything by pointer, is this making the program slower? Should you always just pass arrays as pointer? Thanks!
I wonder if it's worth passing primitive single values like int, float, double or char by pointer? What are you trying to accomplish? Do you want to be able to write to the passed in value? Or do you just need to use it? If you want to write to it, the idiomatic way is to pass by reference. If you don't need to writ...
5,991,981
5,992,189
Virtual destructor when using upcasting
Everyone says that a destructor should be virtual when at least one of class methods is virtual. My questions is, isn't it correct to say that a destructor should be virtual when using upcasting ? class A { public: ~A(){ cout << "Destructor in A" << endl; } }; class B: public A { public: ~B(){ ...
a destructor should be virtual when at least one of class methods is virtual This is a rule of thumb which arises from the fact that when you use virtual functions you are using runtime polymorphism and are more likely to run into situations were you need to destroy a class that may be of a derived type when all you ...
5,992,192
5,992,313
quicksort (n arrays should be treated as 1 and values remapped as needed)
I have a linked list of arrays (struct at bottom of post) Each array may have values like the below example Array1[] = {6,36,8,23}; Array2[] = {8,23,5,73}; Array3[] = {2,5,1,9}; I need to sort these so that all 3 arrays are treated as 1 large array... I need to use quicksort so that it uses in-place processing... I am...
It's not that hard, more an interfacing issue then an algorithmics issue. Write a wrapper container that provides an interface for accessing members and writing (say operator[] in C++) and internally it maps the size_t index argument to the right array. This wrapper class does need the size of every array though to be ...
5,992,645
5,993,164
searching for c++ code parser to see all signatures
I'm looking for a c++ parser which is able to extract all the functions and methods with its signatures. Is there something like this? I had a look at gccxml there I have the problem, that it is not able to use namespaces and its not fine when only a header file is present.
The Clang compiler obviously has the functionality to do this, if I remember correctly there's even an API to access the code tree generated by the parser.
5,992,800
5,992,813
PHP using c++ extension will be faster?
I'm now building a recommender system(a web site). I want to use the PHP as the script language. The recommender system may do complex matrix computing or something else. Considering the performance,I want to use C++ to do matrix computing or other complex computing. So I need the PHP call C++ function, get the result ...
Yes, using a C++ extension for complex calculations will give you a significant speedup over PHP. Check out these questions for more details to go about doing this: How can I use C++ code to interact with PHP? Extending PHP with C++?
5,992,953
5,992,985
C++ cannot convert 'const char*' to 'std::string*'
I have this code below and I'm getting the error upon compilation: error: cannot convert 'const char*' to 'std::string*' for argument '1' to 'void sillyFunction(std::string*, int)' #include <iostream> #include <string> using namespace std; int counter = 0; void sillyFunction(string * str, int cool=0); int main(){ ...
Don't take your parameter in as a string * try just using a const string & instead EDIT: std::string and const char* are different types. the std::string already has a conversion from string literals (ex: "Cool") to the actual string object. So by passing in the string literal "Cool" you are in a sense passing in a s...
5,993,045
6,596,893
Api for capturing voice from microphone with volume regulation
I trying to create application on qt with capability of making voice calls through GSM modem. Now i'm searching for library which can capture voice from micro and has ability to regulate voice volume. Qt's phonon have voice regulation, but does not have ability to capture data from microphone. From the other side, the...
finally I done this with QtMultimedia + subclassing QIODevice. On input and output I have pcm format, signed, so I just multiply byte value of input\output stream with some float value to set volume level, after that I write data to device i need. class VOICEIO_EXPORT VoiceIOAdapter : public QIODevice { Q_OBJECT p...
5,993,050
5,993,226
Function pointers in Objective C
I came across the following code while debugging. I was able to get the result correctly but I didn't not understand the function pointers defined in here. Here pNewMsgeFunc is the alias name of the function pointer tNewMsg which is created inside the structure stRsStruct. RsMsg.h typedef RsMsg* (*tNewMsg)(void); tNewM...
Here pNewMsgeFunc is the alias name of the function pointer tNewMsg which is created inside the structure stRsStruct No, it's not. tNewMsg is a name that identifies a type. typedef RsMsg* (*tNewMsg)(void); ...but pNewMessageFunc is an object of that type. Look at it this way. In this code: typedef unsigned int uin...
5,993,369
5,993,409
searching for a BNF (for yacc) grammar of C++
I found something similar here: Where can I find standard BNF or YACC grammar for C++ language? But the download links don't work anymore, and I want to ask if somebody know where I can download it now?
Looking here: http://www.parashift.com/c++-faq-lite/compiler-dependencies.html#faq-38.11, I found this: http://www.computing.surrey.ac.uk/research/dsrg/fog/CxxGrammar.y
5,993,513
5,997,442
CDatabase thread safety
I am using CDatabase to establish connection with a ODBC database. My concerns are Are operations on CDatabase and related classes thread safe? one of threads will open a connection (using OpenEx) on program stratup and then other threads will perform CRUD database operations. Will thiswork fine without any threading ...
Operations on CDatabase are not fully thread safe, and CRecordset even less. Each thread should use it's own instance of a CRecordset object. http://msdn.microsoft.com/en-us/library/xx6t3y0x.aspx
5,993,880
5,994,039
Not able to befriend typedefs: any particular reason?
struct A {}; typedef A B; struct C { friend struct B; }; GCC 4.7.0 20110427 tells me error: using typedef-name 'B' after 'struct'. So far, this seems pretty self-explanatory; after all, my example code is trying to declare-and-friend a struct called B, which is in fact not a struct-key. However, I have to write frien...
You can befriend arbitrary types (for non-class types, the friend declaration will be ignored), but then you shall omit struct: struct A {}; typedef A B; struct C { friend B; // equivalent: friend struct A; // equivalent: friend A; friend int; // ignored };
5,994,001
5,994,062
My virtual function wont work C++
I have edited this from my real code, so that it is a little easier to understand. The base class: class MWTypes { public: virtual long get() { return (0); } }; The derived class: (There are going to be other classes like char, double etc etc . . .) class TypeLong : public MWTypes { public: TypeLong(long& r...
MWTypes returned = rowSet.getElement(); // lastly I want to get the value in the returned type long foo = returned.get(); should be MWTypes* returned = &rowSet.getElement(); // lastly I want to get the value in the returned type long foo = returned->get(); or MWTypes& returned = rowSet.getElement(); // actua...
5,994,101
5,994,829
Handling a C++ libsigc++ signal with a lambda function
I'm working on some C++ code that uses libsigc++ for signaling (eventing.) I'm quite new to C++, and I tend to think in C#. The equivalent code to what I want in C# would be something like: var names = new List<string>(); thing.Happened += (string name) => names.Add(name); thing.DoStuff(); The libsigc++ tutorials do ...
Lambdas are just function objects. So anywhere you can use an arbitrary(i.e. templated) functor, you can use a lambda. I don't have the library installed, so I can't test this, but looking at this example, I believe this modification should work: int main() { AlienDetector mydetector; auto warn_people = []() {...
5,994,130
5,994,167
win32 CreateProcess cannot convert parameter 2 from 'char *__w64 ' to 'LPWSTR' error
hello all i have code from open source project that im integrating into my code . now my code settings in visual studio 2008 character set is Unicode . and the external code is Multi-Byte Character Set. when i change the character setting in my application after adding the new source im getting other errors in my ...
For the first one use vector<wchar_t> instead of vector<char>. For the second one use L"ERROR: API = %s.\n error code = %d.\n message = %s.\n" instead of "ERROR: API = %s.\n error code = %d.\n message = %s.\n" (note the L at the start.
5,994,302
5,994,326
C++ sizeof wrapper class
Suppose I have a class A that does not inherit from anything, has no virtual methods, and has exactly one variable of type T. Does C++ guarantee sizeof(A) == sizeof(T)? EDIT: Also if T were a composite type, would it make a difference?
No, it might be more than sizeof(T) due to padding.
5,994,399
5,994,429
C++ Memory Leak - What do I delete, and where?
A memory leak exists in the following function. The trouble I am having is knowing how, when, where, and what to delete. Here is the code: #include "stdafx.h" #include <iostream> void someFunc(double** ppDoubleArray, int length) { double* pNewDoubleArray = new double[length]; for(int i = 0; i < length; i++) ...
You are allocating & deleting an array in the function. And you are also returning it. int main() { // This one is allocated on the stack, so it will be deleted when exiting main() double dbls[] = { 1, 2, 3, 4, 5 }; double* pArray = dbls; //... // Your function allocates some memory now pointed at by pA...
5,994,692
5,994,741
Finely Control the output of GCC
For some reasons, I want to be able to fine tune the final executables generated for my C++ program - down to individual instructions. As I recall, GCC should generate some text assembler file as intermediate output before feeding it to the assembler for generating the final binary object file. Is it possible for me t...
Take a look at the -S flag: g++ -S file.c -o output.s Then make your fine tuning on output.s and compile the final executable with: g++ output.s -o application
5,994,999
5,995,283
Problem using pair with accumulate
I am using a deque so I can generate rolling averages and variances for my data. I store n and n^2 as a pair in the deque and then use accumulate with my own operator+(). #include <deque> #include <numeric> #include <utility> template <typename T1, typename T2> std::pair<T1,T2> operator+(const std::pair<T1,T2>& lhs, c...
std::pair doesn't have an operator+, and you haven't provided a way for std::accumulate to call your implementation of operator+. I would wrap the functionality you provided in operator+ in a functor... template <typename T1, typename T2> struct pair_sum : public std::binary_function< std::pair<T1,T2>, std::pair<T1,T2>...
5,995,295
5,995,456
How to receive notification of NSTextField textDidEndEditing from C++?
I have an Objective-C++ program that uses an NSSearchField. Specifically, the NSSearchField is wrapped in a QMacCocoaViewContainer derivative (Qt). How can I set things up so that I can receive notification of textDidEndEditing from a Qt signal? Will I need a pure Objective-C class that uses NSNotificationCenter?
If you're on iOS4, looks like you can have your notification delivered to a block instead. NSNotificationCenter sports this method: - (id)addObserverForName:(NSString *)name object:(id)obj queue:(NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *))block NS_AVAILABLE(10_6, 4_0); Then you could do something ...
5,995,392
5,995,498
VC++ 6 Linker Errors
Basically, what's happening is this: I have a VC6 workspace (contains 3 projects total), and after NOT being able to succesfully port it into VS2010, I installed XP on a virtual machine (Win 7 on host machine), and installed VS6 on the devbox. From there, I was able to get past compilation errors, and land headfirst i...
My first guess would be you haven't added the .lib file to the additional imports of the other projects. If you have dumpbin the binaries and see if you see the export.
5,995,433
5,995,512
Removing console window for Glut/FreeGlut/GLFW?
Under Visual C++, I have played around with Glut/FreeGlut/GLFW. It seems that everyone of these projects adds a CMD window by default. I tried removing it going under: Properties->C/C++->Preprocessor->Preprocessor Definitions From here, I remove the _CONSOLE and replace it with _WINDOWS Then I went under: Properti...
Non-console Windows applications use the WinMain() entry point convention. Your Glut examples probably use the standard C main() convention. If you want a quick fix just for the demo app, the WinAPI function FreeConsole() might help. MSDN: http://msdn.microsoft.com/en-us/library/ms683150(v=vs.85).aspx
5,995,497
5,995,551
What does ::template mean other than making TMP compile
Possible Duplicate: Using template parameters as template parameters Here's a code snippet of some heavily templated container classes used to bind an arbitrary amount of fields of arbitrary types. A co-worker of mine found that my code didn't compile under GCC and after much research he found the fix to get it to ...
It tells the compiler that AddBinding is a template -- since the definition of AddBinding is dependent on T, the compiler wouldn't otherwise know this at the right stage of the compilation process (I'm no expert on the details, but it's to do with the C++ compilation model AFAIK). By writing template after the ::, you ...
5,995,664
5,995,711
Why are there so many different ways to use new operator in C++
I've just read the new operator explanation on the cplusplus.com. The page gives an example to demonstrate four different ways of using new operator as following: // operator new example #include <iostream> #include <new> using namespace std; struct myclass {myclass() {cout <<"myclass constructed\n";}}; int main () {...
Because they have different purposes. If you didn't want new to throw std::bad_alloc on failure, you would use nothrow. If you wanted to allocate your objects in existing storage, you would use placement new … if you want raw, uninitialized memory, you would invoke operator new directly and cast the result to the targe...
5,995,774
6,129,430
Forward-declared type and "non-class type as already been declared as a class type"
I have problem with following code: template <typename T> void foo(struct bar & b); struct bar {}; int main(){} It compiles successfuly on GCC, but fails on MSVC (2008) with following error: C2990: 'bar' : non-class type as already been declared as a class type Is the code wrong or it's a bug in MSVC? It works...
And we have our winner: https://connect.microsoft.com/VisualStudio/feedback/details/668430/forward-declared-type-and-non-class-type-as-already-been-declared-as-a-class-type Thank you for reporting this issue. This is indeed a case of non-conformant behaviour in VC++. However, a simple workaround is to reorder ...
5,995,842
5,996,081
How do you use table models
I understand the core concept, but how do you use Qt table models? How would you go by creating a model class and finally does a QTableView auto-reload when data is changed.
What about reading the Qt Model/View Tutorial?
5,996,046
5,996,302
Invoking a function by address
I am trying to learn a few different methods of calling functions by address. bool gl_draw_text(uint x, uint y, uint color, uint alpha, char *fmt); This function is what I'm calling. The following, is how I'm currently calling it. (And it works fine.) static void glDrawText(char* text, int x, int y) { DWORD func = 0x...
This code compiles (see http://ideone.com/celq1): typedef unsigned int uint ; int main() { bool (*draw)(uint, uint, uint, uint, const char*); draw = reinterpret_cast<bool (*)(uint, uint, uint, uint, const char*)>(0x10057970); draw(20, 20, 14, 255, "Text"); } But of course it doesn't run :-) PS I changed ch...
5,996,278
5,996,414
How to get a type relative to a runtime index?
Let's say I have a boost::mpl::list< A, B, C ...>. How do I access one of those types given an index value at runtime? Is it even possible?
http://www.boost.org/doc/libs/release/libs/mpl/doc/refmanual/for-each.html you basically have to iterate over the entire list and introduce some sort of conditional: eg: struct F { void operator(T &t) { if (i_ == index) ... ++i; } int index = ...; int i_ = 0; }; for_each< L >( F(index) )...
5,996,384
5,996,635
Bitwise shift operation on a 128-bit number
Lets say that I have an array of 4 32-bit integers which I use to store the 128-bit number How can I perform left and right shift on this 128-bit number? Thanks!
void shiftl128 ( unsigned int& a, unsigned int& b, unsigned int& c, unsigned int& d, size_t k) { assert (k <= 128); if (k >= 32) // shifting a 32-bit integer by more than 31 bits is "undefined" { a=b; b=c; c=d; d=0; shiftl128(a,b,c,d,k-32); } ...
5,996,392
6,095,816
Lost the connection to database when using switch statment
I have stackedwidget with multiple pages, at page one, I check the connection, page two, I check the availability of user, and so on for the rest of page(I have five), basically, other pages depend in the first page, if the connection failed or not, my problem is about other pages, even the connection made with out any...
From the documentation: Warning: You must load the SQL driver and open the connection before a QSqlQuery is created. Also, the connection must remain open while the query exists; otherwise, the behavior of QSqlQuery is undefined. So I have to declare QSqlQuery query variable at each case statment, now my pr...
5,997,145
5,997,174
A general question regarding the correct way to implement a dictionary data structure
in any dictionary data structure there is an add_to_ds function which receives the data needed to insert as a parameter. the question is this:should the add_to_ds get the object it self (type T) and do the memory allocation,or should the add_to_ds get a pointer to object and just insert the pointer (type T*,whoever use...
There isn't any generally right / wrong way to do it. If you trust the caller not to modify the memory, you're fine storing a pointer. If, however you don't specify this in your interface, you'll have to duplicate the memory. If you let them enter pointers, they will be responsible with freeing memory, not touching it...
5,997,258
5,997,384
Strange "unsigned long long int" behaviour
Possible Duplicate: How do you printf an unsigned long long int? #include <cstdio> int main () { unsigned long long int n; scanf("%llu",&n); printf("n: %llu\n",n); n /= 3; printf("n/3: %llu\n",n); return 0; } Whatever I put in input, I get very strange output, for example: n: 1 n/3: 2863311...
The problem is that MinGW relies on the msvcrt.dll runtime. Even though the GCC compiler supports C99-isms like long long the runtime which is processing the format string doesn't understand the "%llu" format specifier. You'll need to use Microsoft's format specifier for 64-bit ints. I think that "%I64u" will do the t...
5,997,329
5,997,458
Overload on ostream in a variadic template function
I have a variadic function that I want to overload on the first parameter type. void write( void ) { } void write( std::ostream& ) { } template< typename Head, typename... Rest > void write( std::ostream& out, Head&& head, Rest&&... rest ) { out << head; write( out, std::forward<Rest>(rest)... ); } template< t...
That's because ostringstream needs a base conversion to ostream when you pass it to the other template, while it doesn't need any conversion when you pass it to the template that forwards to write(std::cout, ...). So if you pass ostringstream, it selects the more generic template which forwards the ostringstream as an ...
5,997,452
5,997,889
What is the fate of wchar_t in c++0x?
What is the fate of wchar_t in c++0x considering the new character types char8_t, char16_t, and char32_t? More importantly, what about std::wstring, std::wcout, etc? Are the w* family classes deprecated? Are there new std::ustring and std::Ustring classes for new character types?
Nothing happens to wchar_t, it is still implementation specific (and compatible with C). The new types char16_t and char32_t have defined semantics in the new standard. The old wchar_t might be equivalent to one of those, but likely to a different one on different implementations. Or none of them, on some systems. You ...
5,997,574
5,997,650
Objective Memory Comparison
I would like to write an algorithm that compares one memory block with another and provides an objective value, so as to determine the quality of the match. I've investigated memcmp, and all it is really useful for is to determine whether two memory blocks are identical or not. I've written a recursive function to ac...
I think you need to take the absolute value of (*pSrc - *pDst). In "Hello World 1 !", you're getting a 0 for the number position, while in "Hello World 2 !" you're getting a -1, and -1 is less than 0. Also, if you use this on a long section of memory you could run into stack problems, so you might want to make it iter...
5,997,753
5,997,886
Determine class instance of a member in C++
I've never seen this in any language, but I was wondering if this is possible using some trick that I don't know. Let's say that I have a function like struct A { // some members and methods ... some_t t; // more members ... }; void test(some_t& x) { // a reference to avoid copying a new some_t // obtain...
If you know that you have a reference to the t member of some A instance, you can get the instance using container_of, e.g. A* pa = container_of(&x, A, t);. Verifying that the resulting pointer actually is an A is technically possible if and only if A has virtual members, unfortunately there's no portable method to che...
5,997,764
5,997,877
How to handle not being able to store time in an int?
In some languages, time is stored as the number of seconds from the epoch and stored in an int (Correct me if I am wrong). So we will eventually hit a point where we can't store the current time in an int because there won't be enough bits to hold the time. Now I know this is down the road, but still, isn't it worth th...
Your concern is valid if you want to deal with dates reasonably far in the future. With an unsigned 32-bit integer, you can store up to 2^32 seconds, which is a little over 136 years. To answer your question, whether you should use 64 or 32 bits to store the amount of seconds depends on your application's needs. If you...
5,997,956
5,998,303
How to determine if a type is derived from a template class?
How can I determine if a type is derived from a template class? In particular, I need to determine if a template parameter has std::basic_ostream as a base class. Normally std::is_base_of is the tool for the job. However, std::is_base_of only works for complete types not class templates. I'm looking for something li...
I'm not aware of a short and concise way. But you can abuse overloading again template< typename T, typename U > std::true_type is_based_impl( std::basic_ostream<T, U> const volatile& ); std::false_type is_based_impl( ... ); template< typename T > bool is_based_in_basic_ostream( T&& t ) { return decltype(is_based_im...
5,998,347
5,998,497
How to receive NSNotifications from Objective-C in C++ classes?
I have an Objective-C++ class that adds itself as an observer for an event on a Cocoa NSView. I would like to be able to send the NSNotifications to a method of a C++ class instead of an Objective-C method or block. How can I do this? My situation is this: A - Objective-C++ class B - NSView B is encapsulated by A. I ...
Create a dead simple wrapper class in Objective-C that points to your C++ instance and handles the notification by calling the C++ method.
5,998,367
5,998,492
Display a number decimal format instead as an exponential in cout
I calculated a total of floats and I got a number like 509990e-405. I'm assuming this is the short version; how can I cout this as a full number? cout << NASATotal << endl; is what I have now.
You can force the output to be not in scientific notation, and to have the sufficient precision to show your small number. #include <iomanip> // ... long double d = 509990e-405L; std::cout << std::fixed << std::setprecision(410) << d << std::endl; Output: 0.0000000000000000000000000000000000000000000000000000000000...
5,998,388
5,998,933
Searching in a hash table HELP!
I am trying to write a hash table for class and I can't seem to get this while loop working. Do you guys see anything wrong with it? The while loop is ending prematurely, I think there is something wrong with my while loop condition? void search(store t[], string s, int num, int table_size) { int temp = num; bool ...
Your while loop seems ok, but are you sure about the following line ? if(t[num].data == s) cout<<"("<<s<<")"<<" appears "<<t[num].count<<" times."<<endl; shouldn't be the following instead ? if(t[temp].data == s) cout<<"("<<s<<")"<<" appears "<<t[temp].count<<" times."<<endl; Because obviously you are running...
5,998,496
5,998,553
C++ STL map with custom comparator storing null pointers
I'm trying to write a copy constructor for an object managing a STL map containing pointers, where the key is a string. However, when I attempt to insert new values in the map, the pointers are set to NULL: // ... for(std::map<std::string, data_base*, order>::const_iterator it = other.elements.begin(); it != other.elem...
I don't see any problem with this code, other than maybe std::map<std::string, data_base*, order>::const_iterator it Here order gives the key comparator to use to sort the pairs contained in the map (often implemented as a tree). Maybe you're doing something wrong in it, making your [] operator don't find the right k...
5,998,539
5,999,016
template template class with const template parameter
I don't understand why this doesn't compile: struct A {}; template<class T> struct B {}; template<template<class> class T1, class T2> struct C {}; int main (int ac, char **av) { typedef B<double> b; //compiles typedef B<const double> b_const; //compiles typedef B<A> ba; ...
The first argument to C isn't a type, hence it makes no sense to pass in a const-type as its arg. A template can't be const or non-const, only types can be const or non-const. What does const B even mean? const int makes sense. const vector<int> makes sense, as does vector<const int>. But what would const vector mean? ...
5,998,576
5,998,594
How do I check if a value is contained in a vector? C++
I have a vector that I am trying to perform a contains function on. I am receiving some sort of casting error and I can't piece together a solution. I am also wanting to know whether or not what I am doing is the appropriate way to check if a vector contains a value. Here is the code: #include "stdafx.h" #include <vect...
When you declare a variable with it's default constructor, you don't put () after it (although it's optional when you use new to allocate space on the free store). So this line: std::vector<double> vec(); should become std::vector<double> vec; If you leave it as you did, it thinks that line is a function prototype of...
5,998,588
5,998,631
Runtime error in openframworks code I'm not even using
I'm starting a project using the Aubio library within openFrameworks, so I'm copying in code to my project from Aubio demos, modifting, etc. The Aubio function new_aubio_pitchdetection() works great, but the similar function new_aubio_onset() doesn't. In fact, it gives me an EXC_BAD_ACCESS error in the freeImage librar...
The code is most probably corrupting the heap. That can cause widespread problems, just about any code is using the heap. The code that fails is not responsible for the corruption. Diagnose this with a good debug allocator, see what's available in your CRT. Or a thorough code review.
5,999,141
5,999,163
Errors nesting vectors<> within vectors<>
I'm having a problem nesting vectors within vectors, the equivalent of a 2D array in C. I have tried the code demonstrating this posted on numerous website, to no avail. class Board { public: vector< vector<Cell> > boardVect; //Decalre the parent vector as a memebr of the Board class Board() ...
You need to use the initialization list in order to call constructors on the members of your class, i.e.: Board() :boardVect(3, vector<Cell>(3)) {} Once you've entered the body of the constructor, it's too late, all the members are already constructed, and you can only call non-constructor member functions. You c...
5,999,191
6,002,193
Segmentation fault with trivial Spirit Parser grammar
I'm running into frequent segfaults with my Spirit Qi parser. After spending days to debug the issue (I found the stacktraces impossible to grok) I decided to trim it down to a minimal example. Can anyone tell what I'm doing wrong, if anything? Save code as bug.cpp, compile with g++ -Wall -o bug bug.cpp and you should...
Changing the initialization order as you suggested in your answer just hides the problem. The actual problem is, that rule<>'s have proper C++ copy semantics. You can fix this by rewriting your gramar initialization as: bug_demo() : grammar<Iterator, Skipper>(story, "bug"), story(the.alias()), the("the") {...
5,999,219
5,999,782
Correct way to logging elapsed time in C++
I'm doing a article about GPU speed up in cluster environment To do that, I'm programming in CUDA, that is basically a c++ extension. But, as I'm a c# developer I don't know the particularities of c++. There is some concern about logging elapsed time? Some suggestion or blog to read. My initial idea is make a big loop ...
Standard functions such as time often have a very low resolution. And yes, a good way to get around this is to run your test many times and take an average. Note that the first few times may be extra-slow because of hidden start-up costs - especially when using complex resources like GPUs. For platform-specific calls, ...
5,999,449
6,001,622
llvm: generating cleanup destructors before function return
in LLVM, usually you will exit a generated function with CreateRet, however, i want to add cleanup destructors for local objects instantiated in the function. My question is: i assume i have to insert the cleanup function calls before inserting the CreateRet, however, i'm wondering if the return value is one of the loc...
You can codegen your source-language return statement / expressions as copies into the return storage followed by a branch to a designated return basic block, which will destroy locals. If your generated LLVM function returns the value itself, instead of following its own protocol (by returning the value through the fi...
5,999,500
5,999,508
Can C be used to capture system calls on a machine?
Good day, I was wondering if there is a way to do direct system call capture with C or C++? I know that currently on unix systems you can use SystemTap to do system capture. The problem I'm having is that in order to feed them into another program for analysis I have to pipe them to the other program. I'd like to pass...
strace does exactly that. You can take a look at its source code to see how its done.
5,999,620
6,001,828
Overloaded operators & inheritance & templates (A formidable combination)
Greetings all. I am writing some code using the Boost Units library and have run into a problem. I have managed to abstract the problem from Boost code so you won't be looking through reams of boost template meta programming. Though I'm sure if you have experience with that it could help. Here is the reproduction: clas...
Just as I gave up trying to solve this last night the answer hit me like a brick. The Q typed result of U::operator*(Base) is conceptually the same as the Base typed result of operator*(U,Base), even though they are being represented by different Types. All I need to do is provide a constructor for Base ( const Q & ) t...
5,999,841
5,999,853
How can i suppport both Unicode and Multi-Byte Character Set in my code?
i must say im new to win32 c++ programming so i face a problem that some code compile in Multi-Byte Character Set and not in Unicode Character Set. how can my code support both ? for example this NOT compiles in Multi-byte only in Unicode and the commented vector only in MultiByte: //vector<char> str2(FullPathToExe....
Use TCHAR as the character type (e.g. std::vector<TCHAR>), which is: A WCHAR if UNICODE is defined, a CHAR otherwise. This type is declared in WinNT.h as follows: #ifdef UNICODE typedef WCHAR TCHAR; #else typedef char TCHAR; #endif
5,999,999
6,000,008
Is the call stack limit of a program consistent at all across computers?
My knowledge of how the call stack works is limited, but I was basically wondering- if I have a program that results in a stack overflow after X amount of recursions on my own computer (e.g. a while back I made a small program that did so at about 400 recursions on my computer), will this be roughly the same on other c...
It can vary, not only between computers but also between processes and even threads when within a process. When starting a worker thread, there is an option to specify the thread's stack size on many operating systems. On OSes there are different default stack sizes.
6,000,004
6,000,024
Declaring a std::map iterator causes a weird error
I am just trying to declare a map iterator but I get a compile error saying "expected ; before it" I believe it is because I haven't included the whole std namespace (using namespace std;) but I intentionally dont want to include all of it. My code: #include <map> #include <string> template <class Object> class Cont {...
If I'm not mistaken because you are using a template argument you need to prefix the iterator declaration with typename. typename std::map <unsigned int, Object*>::iterator it = m.begin();
6,000,018
6,000,027
What is the use of "static" keyword with Variables, functions and objects of classes etc?
Possible Duplicate: static function/variable Tell me the different combination of static like object static and variable normal , or variable static function normal , object static function normal etc etc
A static variable and function are limited in scope they are declared in. Additionally, variables defined in functions will persist their value across function calls if defined as static. A static method or member on an object can be used directly without a specific instance of the object, i.e. no this pointer will be ...
6,000,111
6,000,158
Store a reference to an objects member variable with a different class
I am trying to create a Container class where I can retrieve an object from the container by using that objects member variable as its identifier. But I get a compile error because I am trying to store a pointer(?)/reference to the objects member variable template <typename Object> class Container { private: ...
Declaring a template data member is not allowed in C++ (not to confuse with template syntax used while defining a static member). The best way to achieve is, template <typename Object, typename dataType> // <-- Add dataType here class Container { private: dataType Object::* memberVariable; // use 'dataTy...
6,000,168
6,000,181
Cannot add pointer to array of class pointers vector
I am trying to add a pointer to an object in a pointer object vector. The 'message_list' vector lists pointers to an abstract class Message which is either adding a new Topic or Reply, two subclasses which inherit the superclass Message. My problem is when I try to add either a new Topic or a Reply to the vector, I get...
void Bboard::add_topic() const Its a const member function which means this function promises not to modify the object, but the fact is that you want to modify the object, as message_list is a member of the class and you're adding item to it. So const is inappropriate here. Just remove it and make it as: void Bboard:...
6,000,238
6,000,297
way to get specific integer(s) from a double data type
C++ So i need a way to get say the number 7 from the double 56.279 or any other of the integers and i cannot figure out how to do it without having the knowledge of what the double returned from my function is going to be (so i cant simply do 56.279 - .009). My function alway returns seconds elapsed as a double in thi...
To have the n decimal number of your double x you can do E((x modulo x*10^(n-1))*10)
6,000,354
6,000,372
how to chop off a few decimals of a double value
Possible Duplicate: way to get specific integer(s) from a double data type C++ So i need a way to get say the number 7 from the double 56.279 or any other of the integers and i cannot figure out how to do it without having the knowledge of what the double returned from my function is going to be (so i cant simply do...
Look at this page: http://www.cplusplus.com/reference/iostream/ios_base/precision/ If you only need to change the display something like setw might appropriate: http://www.cplusplus.com/reference/iostream/manipulators/setw/
6,000,674
6,000,754
Semaphore implementation
I was wondering if there was a way to implement semaphore in C++ (or C#), any libraries that'd help. I tried using OpenMP but I had no way of actually blocking threads, instead I had to busy wait on 'em which lead to deadlocks if/when I hadn't enough number of threads. So First I'm looking for a some library that would...
Are there any libraries out there that already implement this? For C++ there are multiple multithreading libraries, which provide Semaphore implementations: Posix Poco Thread Tiny Threads Also, You can also implement Semaphores using Boost. Check this out.
6,000,829
6,000,840
Is there any concurrent queue library available in c++?
I am wondering if there is any concurrent queue implementation/library available in c++?
The Intel Thread Building Blocks have one: http://threadingbuildingblocks.org/files/documentation/a00129.html. There is also one in the Concurrency Runtime (available with VS 2010) http://msdn.microsoft.com/en-us/library/ee355358.aspx.
6,000,850
6,001,730
Declaring and accessing global objects
The well known method for this is to declare int globalVar = 0 and then -where to use it- extern int globalVar; but that didn't work with me for objects from user defined class! This is an example of what I did: file1.cpp: #include "file2.h" class list { ....}; list * x ; //do something with x` file2.cpp...
error C2143: syntax error : missing ';' before '<' It's "std::queue<errorStruct>", not "queue<errorStruct>".
6,001,015
6,148,072
Design for customizable string filter
Suppose I've tons of filenames in my_dir/my_subdir, formatted in a some way: data11_7TeV.00179691.physics_Egamma.merge.NTUP_PHOTON.f360_m796_p541_tid319627_00 data11_7TeV.00180400.physics_Egamma.merge.NTUP_PHOTON.f369_m812_p541_tid334757_00 data11_7TeV.00178109.physics_Egamma.merge.D2AOD_DIPHO.f351_m765_p539_p540_tid31...
I believe you're over-complicating the design-pattern aspect and glossing over the underlying matching/indexing issues. Getting the full directory listing from disk can be expected to be orders of magnitude more expensive than the in-RAM filtering of filenames it returns, and the former needs to have completed before ...
6,001,272
6,001,315
How can I read a file with read() and O_DIRECT in C++ on Linux?
I'm searching for a solution to solve the above described problem. Here's my "doesn't working code". charsInCurrentBuffer returns always -1! #define BUFSIZE 512 char *bufferA = new char[BUFSIZE]; char *bufferB = new char[BUFSIZE]; const char *inputFile = "in.txt"; if ( (fdInputFile = open(inputFile, O_DIRECT) ) != ...
When you read from an O_DIRECT fd, the "alignment of the user buffer and the file offset must all be multiples of the logical block size of the file system" (quoted from the open man page) on Linux. Other environments might have different constraints on this, and it's in fact filesystem dependent. That's not going to ...
6,001,311
6,001,336
Calling a function from the same header file from two C++ files in the same project
I have a program consisting of 3 files: main.c; other.c and event.h event.h has a function called 'event()'. I'd like to call the event() function from both main.c and other.c. At the top of both main.c and other.c I include the line #include "event.h" ...and within each of the .c files I have the lines event(); Howe...
The definition of the function ie its code can only be given in one place. The header should include just the declaration of the event function and the code implementing the function needs to be in a .c file. e.g. in event.h void event(); and in any ONE .c file - could be either of main.c or other.c or probably bette...
6,001,333
6,001,450
C++: How do i copy multiple objects to the clipboard and extract them after it?
I need to copy a string and a bitmap to the clipboard. I have implemented copying of a string: if(OpenClipboard(NULL)) { HGLOBAL clipbuffer; char * buffer; EmptyClipboard(); clipbuffer = GlobalAlloc(GMEM_DDESHARE, strlen(source)+1); buffer = (char*)GlobalLock(clipbuffer); strcpy(buffer, LPCSTR(source)); GlobalUnlock(cl...
If you are asking about how to put an image and string onto the clipboard such that if you pasted into Microsoft Word then both would appear, you almost certainly want to put data on the clipboard in Rich Text Format. I can't offhand find a good example of code that does this at a low-level using CF_RTF. An easier hig...
6,001,356
6,001,584
Does a private new operator have any unexpected side effects?
I read in this blog, that making the new operator private is a good approach to enforce instantiation on the stack. I am implementing a class that employs the RAII idiom. This class should obviously only be instantiated on the stack, so I am looking for a way to enforce that. My question is, does this have any side ef...
I am implementing a class that employs the RAII idiom. This class should obviously only be instantiated on the stack, so I am looking for a way to enforce that. That is not RAII. RAII is initializing when constructing and de-initializing in destructors. RAII is about resources you control (e.g. data members) and no...
6,001,376
6,001,419
How do I call dataChanged
The following is my add a row class. It is called by the code, not the table and I want it to properly call dataChanged when a new row is added, although this isn't working, the table doesn't do anything. What am I doing wrong? void MyModel::add(const Person& p) { people.push_back(p); QModelIndex top = create...
dataChanged works only on existing data, you need to call beginInsertRows() / endInsertRows() void MyModel::add(const Person& p) { beginInsertRows(QModelIndex(), people.count(), people.count()); people.push_back(p); endInsertRows(); QModelIndex top = createIndex(people.count() - 1, 0, 0); QModelInd...
6,001,447
6,001,491
Narrowing type conversion in C++ using pointers
I have been having some problems with downward type conversion in C++ using pointers, and before I came up with the idea of doing it this way Google basically told me this is impossible and it wasn't covered in any books I learned C++ from. I figured this would work... long int TheLong=723330; int TheInt1=0; int TheInt...
TheInt2 = *pTheLong2; This invokes undefined behavior, because the C++ Standard does not give any guarantee as to which memory location pTheLong2 is pointing to, as it's initlialized as: long int * pTheLong2 = &TheLong + 0x4; &TheLong is a memory location of the variable TheLong and pTheLong2 is initialized to a memo...
6,001,519
6,001,540
Set digit of a hexadecimal number
How can I set a digit in a hexadecimal number? I currently have this code: int row = 0x00000000; row |= 0x3 << 8; row |= 0x2 << 4; row |= 0x1 << 0; printf("Row: 0x%08x", row); Which works perfectly fine as long as "row" is just zeros. As soon as I change it to something like this: int row = 0x33333333; row |= 0x3 <<...
You should delete (make it 0) the digit first. row &= ~(0xf << 4); ~ operator reverses the values of all bits in the number. So. 0x000000f0 becomes 0xffffff0f. Your code should look like: row &= ~(0xf << 8); row |= 0x3 << 8; row &= ~(0xf << 4); row |= 0x2 << 4; row &= ~(0xf << 0); row |= 0x1 << 0;
6,001,565
6,001,620
Limit occurrences of an event
I have a function that controls a bulb. The bulb is programmed to flash whenever a key is pressed. However, I want to limit the minimum interval between flashes to prevent the bulb from burning out. The bulb is controlled by a relay switch connected to the serial port, and the code is as follows: void WINAPI flash (HIN...
You could use a simple variable that keeps the time as reported by QueryPerformanceCounter. The accuracy of QPC is very, very high on most systems. On my system, the frequency is 2.8million- or one tick per ten processor clocks. class bulb { __int64 clocks; __int64 frequency; public: static const int max_ms...