question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
3,000,992
3,001,143
How C++/Qt - Memory allocation works?
I recently started investigating Qt for myself and have the following question: Suppose I have some QTreeWidget* widget. At some moment I want to add some items to it and this is done via the following call: QList<QTreeWidgetItem*> items; // Prepare the items QTreeWidgetItem* item1 = new QTreeWidgetItem(...); QTreeWid...
A quick peek into qtreewidget.cpp shows this: void QTreeWidget::clear() { Q_D(QTreeWidget); selectionModel()->clear(); d->treeModel()->clear(); } void QTreeModel::clear() { SkipSorting skipSorting(this); for (int i = 0; i < rootItem->childCount(); ++i) { QTreeWidgetItem *item = rootItem->children...
3,001,121
3,001,207
Else statement crashes when i enter a letter for a cin << int value
Alright, I have a question, I veered away from using strings for selection so now I use an integer. When the user enters a number then the game progresses. If they enter a wrong character it SHOULD give the else statement, however if I enter a letter or character the system goes into an endless loop effect then crashes...
Your problem is not with the else-statement, but with your input. If you do something like cin >> i; and enter a character, the streams error state is set and any subsequent try to read from the stream will fail unless you reset the error state first. You should read a string instead and convert the strings contents t...
3,001,266
3,001,371
Trying to zoom in on an arbitrary rect within a screen-aligned quad
I've got a screen-aligned quad, and I'd like to zoom into an arbitrary rectangle within that quad, but I'm not getting my math right. I think I've got the translate worked out, just not the scaling. Basically, my code is the following: // // render once zoomed in glPushMatrix(); glTranslatef(offX, offY, 0); glScalef(?...
When I've needed to do this, I've always just changed the parameters I passed to glOrtho, glFrustrum, gluPerspective, or whatever (whichever I was using).
3,001,336
3,001,352
C++: Delete a struct?
I have a struct that contains pointers: struct foo { char* f; int* d; wchar* m; } I have a vector of shared pointers to these structs: vector<shared_ptr<foo>> vec; vec is allocated on the stack. When it passes out of scope at the end of the method, its destructor will be called. (Right?) That will in turn...
delete foo; will delete the memory allocated to the foo structure, which includes the three pointers. But the memory pointed to by the pointers themselves will only be deleted if you implement a destructor that explicitly deletes them.
3,001,413
3,001,887
How do I obtain a code point integer from a 1 to 4 byte UTF-8 encoded sequence in Windows?
I am Patrick Niedzielski, a programmer for the Free Software 3D adventure game Humm and Strumm. I'm working on a minimal Unicode character class in C++. I currently have an array of four bytes representing a UTF-8 sequence. On GNU/Linux, I can just convert to UTF-32 with iconv(), but on Windows, I cannot do this. Is...
I recently posted C/C++ code for decoding a UTF-8 sequence to UTF-32: How do I read UTF-8 characters via a pointer? Validate Unicode String and Escape if Unicode is Invalid (C/C++)
3,001,419
3,001,454
Getting input in system() function (Mac)
#include <iostream> using namespace std; int main() { short int enterVal; cout << "enter a number to say: " << endl; cin >> enterVal; system("say "%d"") << enterVal; return 0; } Is what I am currently trying. I want the user to enter a number and the system() function says it basically. The code...
You must format the string manually. #include <iostream> #include <sstream> using namespace std; int main() { short int enterVal; cin >> enterVal; stringstream ss; ss << "say \"" << enterval << "\""; system(ss.str().c_str()); }
3,001,548
3,001,749
Is there a 2003 compatibility setting in Visual Studio 2008 (compiler compatibility, not project / solution files)
I have a Visual Studio 2003 solution that I've opened with VS2008, and it converted successfully. However, it won't build because the code contains some things that were acceptable under Visual Studio 2003, but simply don't fly under Visual Studio 2008. Changing the code would be really difficult in my particular situa...
There is not a compatibility switch. You'll have to install VS2k3 if you can't update the source code.
3,001,579
3,001,605
C++ WCHAR: Cannot allocate an array of constant size 0
I'm trying to create a WCHAR: LONG bufferSize = foo.bar() + 1; WCHAR wszBaz[bufferSize]; The compiler issues an error: error C2057: expected constant expression error C2466: cannot allocate an array of constant size 0 error C2133: 'wszBaz' unknown size What am I doing wrong? UPDATE: I added const but it still gives t...
Array sizes must be constant expression: const int foo = 10; WCHAR array1[123]; // ok - 123 is a constant expression WCHAR array2[foo + 10]; // ok too - the expression is constant WCHAR array3[bar(123)]; // not ok - it may evaluate to the same thing every time, but function calls aren't seen as constant. Note that con...
3,001,615
4,663,788
Qt moc with implementations inside of header files?
Is it possible to tell the Qt MOC that I would like to declare the class and implement it in a single file rather than splitting them up into an .h and .cpp file?
I believe this to be the best way. It's actually how I construct all of my objects now. Qt 4.8.7 Works.pro: SOURCES += \ main.cpp HEADERS += \ Window.h \ MyWidget.h main.cpp #include <QtGui> #include "Window.h" int main(int argc, char *argv[]) { QApplication app(argc,argv); Window window; wi...
3,001,653
3,001,670
How can I access the sign bit of a number in C++?
I want to be able to access the sign bit of a number in C++. My current code looks something like this: int sign bit = number >> 31; That appears to work, giving me 0 for positive numbers and -1 for negative numbers. However, I don't see how I get -1 for negative numbers: if 12 is 0000 0000 0000 0000 0000 0000 0000 ...
The result of right-shifting a negative number in C++ is implementation-defined. So, no one knows what right-shifting your -12 should get on your specific platform. You think it should make the above (1), while I say that it can easily produce all-ones pattern, which is -1. The latter is called sign-extended shifting. ...
3,001,679
3,001,699
Why do I get corrupt output on my file?
I have a simple program which I have compiled in both MinGW and Visual C++ 2008 Express, and both give an output file larger than 88200. When I set s = 0, both programs work as expected. What am I doing wrong? #include <fstream> using namespace std; int main(int argc, char *argv[]) { int i; short s; fs...
Try: f.open("test.raw", ios_base::out | ios_base::binary); When you write out chars that happen to match the newline character \n they are being converted to the standard windows newline sequence \r\n. Opening the file in binary mode stops this conversion from being performed.
3,001,805
3,001,817
The ** idiom in C++ for object construction
In a lot of C++ API'S (COM-based ones spring to mind) that make something for you, the pointer to the object that is constructed is usually required as a ** pointer (and the function will construct and init it for you) You usually see signatures like: HRESULT createAnObject( int howbig, Object **objectYouWantMeToIniti...
"Besides wanting error codes"? What makes you think there is a besides. Error codes are pretty much the one and only reason. The function needs some way to indicate failure. C doesn't have exceptions, so it has to do that through either a pointer parameter, or the return value, and the return value is idiomatic, and ...
3,001,938
3,002,034
get resulting verticies from a gltransformation?
I have some verticies and then I apply a glrotate(). I'd want to now what my verticies became after this transformation. How could I do this? Thanks
Again? You can't do that. There is a feedback buffer, but that's not what you are looking for. Read my previous explanation for details.
3,002,022
3,002,156
How do games move around objects (in general)
I'm sure there's not just 1 answer to this but, do game engines actually change the vectors in memory, or use gltransformations? Because pushing and popping the matrix all the time seems inefficient, but if you keep modifying the verticies you cant make use of display lists. So I'm wondering how it's done in general. T...
Depends on your goals/objects. Objects that never change are moved by setting matrices (it is possible to do that using glRotatef/glTranslatef and such too). It is certainly faster than transforming object vertex by vertex. Object is stored in DisplayList, VertexArray or in VBO. You CAN send entire object every time us...
3,002,084
3,002,662
Intra-Unicode "lean" Encoding Converters
Windows provides encoding conversion functions ("MultiByteToWideChar" and "WideCharToMultiByte") which are capable of UTF-8 to/from UTF-16 conversions, among other things. But I've seen people offer home-grown 30 to 40 line functions that claim also to perform UTF-8 / UTF-16 encoding conversions. My question is, how r...
The open source ICU library has 113 lines of code for ucnv_fromUnicode_UTF8 (source/common/ucnv_u8.c). Error checking included, proper surrogate handling, some comments. You should only consider using something else if you don't like the naming conventions.
3,002,101
3,004,223
How can I Violate Encapsulation property?
How can I Violate Encapsulation property without having a compile time error? (in C++) just so curious.. This was actually a question asked by one of my professor.. Please don't misunderstand. This was asked when we had a discussion over compiler error's
#define private public #define protected public #define class struct There you go :-)
3,002,110
3,002,124
#include in .h or .c / .cpp?
When coding in either C or C++, where should I have the #include's? callback.h: #ifndef _CALLBACK_H_ #define _CALLBACK_H_ #include <sndfile.h> #include "main.h" void on_button_apply_clicked(GtkButton* button, struct user_data_s* data); void on_button_cancel_clicked(GtkButton* button, struct user_data_s* data); #endi...
Put as much as you can in the .c and as little as possible in the .h. The includes in the .c are only included when that one file is compiled, but the includes for the .h have to be included by every file that uses it.
3,002,115
3,003,504
Iterator for boost::variant
Hy there, I'm trying to adapt an existing code to boost::variant. The idea is to use boost::variant for a heterogeneous vector. The problem is that the rest of the code use iterators to access the elements of the vector. Is there a way to use the boost::variant with iterators? I've tried typedef boost::variant<Foo, Ba...
Well of course there is. Dereferencing the iterators will naturally yield a boost::variant<...> reference or const-reference. However it does mean that the rest of code should be variant-aware. And notably use the boost::static_visitor to execute operations on the variants. EDIT: Easy! struct Printer: boost::static_vis...
3,002,123
3,002,182
C++: Best way to copy a section of WCHAR[] into a wstringstream?
I have a WCHAR[], a wstringstream, and an arbitrary section of the WCHAR[] that I want to copy into the wstringstream. What is the best way to do this? It seems that there must be a better way than this: for (int i = start; i < start + length; i++) { wszStringStream << wchr[i]; }
Sure. Try this: wszStringStream.write(wchr+start, length);
3,002,163
3,002,180
Using memcpy in the STL
Why does C++'s vector class call copy constructors? Why doesn't it just memcpy the underlying data? Wouldn't that be a lot faster, and remove half of the need for move semantics? I can't imagine a use case where this would be worse, but then again, maybe it's just because I'm being quite unimaginative.
Because the object needs to be notified that it is being moved. For example, there could be pointers to that given object that need to be fixed because the object is being copied. Or the reference count on a reference counted smart pointer might need to be updated. Or.... If you just memcpy'd the underlying memory, the...
3,002,183
3,002,407
Best way to render Tesselated Objects (OpenGL)
I'm using the GLUTesselator for Polygons. Right now the vertex callback does glvertex2f and gltex2f. Would it be better simply to collect the verticies from the vertex callback in a std::vector then use gldrawarrays()? Or would this actually be less efficient since it has to put the verts and texture coordinates in a v...
If the vertex count on your tessellated objects is "sufficiently large" VAs/VBOs are almost always going to be faster than immediate-mode glBegin()/glEnd() code, especially if your geometry is static.
3,002,338
3,002,343
determining True/False
the following code #include <iostream> using namespace std; int main(){ char greeting[50] = "goodmorning everyone"; char *s1 = greeting; char *s2 = &greeting[7]; bool test = s2-s1; cout << "s1 is: " << s1 << endl; cout << "s2 is: " << s2 << endl; if (test == true ){ cout << "test...
If the result of the subtraction is zero, test will be false; otherwise it will be true. Any value that is of a numeric type, enumeration type, or is a pointer can be converted to a boolean; if the value is zero (or null, for pointers), the result is false; otherwise the result is true.
3,002,389
3,002,484
C++ - Basic WinAPI question
I am now working on a some sort of a game engine and I had an idea to put everything engine-related into a static library and then link it to my actual problem. Right now I achieved it and actually link that library and every functions seem to work fine, except those, which are windows-related. I have a chunk of code i...
Ah, maybe you've run into this problem described in an MSDN blog: If you're writing a static library, you may have need to access the HINSTANCE of the module that you have been linked into. You could require that the module that links you in pass the HINSTANCE to a special initialization function, but odds are that peo...
3,002,395
3,002,429
is there a way to use c++0x at xcode? I want to use gcc 4.4 or greater
I want to use gcc 4.4 or greater for iphone developement. anyone know how?
No you don't. Trust me you don't. Apple stays at gcc 4.2.1 because 4.2.2 and higher use the GPLv3 which means they'd have to give up control of their platform (a big problem for the iphone sdk). So they don't upgrade. Unfortunately for you, you can't exactly just drop in a replacement gcc either, due to custom patches,...
3,002,433
3,002,469
function objects versus function pointers
I have two questions related to function objects and function pointers, Question : 1 When I read the different uses sort algorithm of STL, I see that the third parameter can be a function objects, below is an example class State { public: //... int population() const; float aveTempF() const; ...
PopLess() instantiates a temporary instance of the class PopLess to be passed to std::sort(). It's effectively the same as if you were to say (note that in this example an extra copy is made): PopLess pl = PopLess(); sort(union, union + 60, pl); Then, std::sort() will call the operator() on that instance. As for whet...
3,002,487
3,002,521
Simple/efficient text compression
What's the simplest, but efficient compression algorithm? Deflate, lzma, etc. aren't valid options. I need something that compiles really small, like: RLE, LZX, Huffman, etc.. Note: The data is 95% ASCII text Edit: Data is ~20kb at the moment, but i expect it to grow up to 1mb Edit2: Other interesting options smaz http...
It sounds like LZO was designed to meet your requirements: Decompression is simple and very fast. Requires no memory for decompression. Compression is pretty fast.
3,002,571
3,002,588
Gradients and memory
I'm creating a drawing application with OpenGL. I'v created an algorithm that generates gradient textures. I then map these to my polygons and this works quite well. What I realized is how much memory this requires. Creating 1000 gradients takes about 800MB and that's way too much. Is there an alternative to textures, ...
Yes... gradients are super easy to do in OpenGL; you don't need textures at all. Working from memory here... you'd just do something like this: glBegin(GL_POLYGON); glColor3ub(255,0,0); // red glVertex2f(-1,-1); glVertex2f(1,-1); glColor3ub(0,0,255); // blue glVertex2f(1,1); glVertex2f(-1,1); glEnd(); // draws a square...
3,002,617
3,002,632
Compare List/set elements
I'm looking to compare two sets and display the missing elements in second set by iterating over the first set. I've done using lists but it seems like an overhead iterating over the unordered list to find the elements. #include <iostream> #include <list> using std::list; bool isExist(list <int> &original, int i) { l...
If you have two sets: std::set<int> s1; std::set<int> s2; and you want to get the set of elements that are in one but not the other, you can use std::set_difference: std::set<int> difference; std::set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(), std::inserter(differenc...
3,002,646
3,002,700
C++ template instantiation with identity argument
I have ran into yet another problem I do not understand. The following does not instantiate (argument instantiation fails), why? template<class E> void operator[](typename boost::mpl::identity<E>::type e) const; thank you for your help
identity can be used to force you to specify the template argument explicitly. It effectively prevents that function parameter from partaking in template argument deduction. A qualified type name is one of the non deduced contexts; that is, identity<E>::type will not be used to deduce the template parameter for E. For...
3,002,867
3,003,755
How to debug c++ DirectShow filter
What debugging tools are available for directshow filters? Presently, I have a project that compiles and registers a video source filter that I then setup a graph in GraphEdit. I am using c++ in visual studio 2008. Is it possible to get a debugger attached to the filter in any way where I could set break points, ins...
There should be no problem with attaching a debugger. Set graphedt.exe as the debug target in your filter's Visual Studio project and you should be able to set breakpoints in your code. If you're having difficulty with this, it might be because of the anti-debugging logic in some decoders — you'll have to avoid using t...
3,003,022
3,008,345
Boost ASIO async_accept compilation fails
Man... thought using ASIO in Boost was going to be easy and intuitive. :P I am starting to get it finally but I am having some trouble. Here's a snippet. I am having several compiler errors on the async_accept line. What am I doing wrong? :P I've based my code off of this page: http://www.boost.org/doc/libs/1_43_0/doc/...
async_accept expects a reference to the socket, not a pointer, so try acceptor->async_accept(*tempNewSocket, ...
3,003,165
3,003,341
Why does update to a dll need recompilation and sometime not?
Why does update to a dll need recompilation and sometime not?
This is called "Binary Compatibility". Keeping this compatibility is not easy, and the information on this are very spare. You should google and test it yourself. Here are some (incomplete) guide for keeping the compatibility: http://techbase.kde.org/Policies/Binary_Compatibility_Issues_With_C++ http://techbase.kde.or...
3,003,308
3,003,423
General practice to specify a break after a default clause?
Possible Duplicate: break in a case with return.. and for default If I have a switch statement: switch() { case 1: ... case 2: ... ... default: break; } Is there any reason for the break in the default clause? I see this in quite a few places, but isn't it unnecessary? What is the general pr...
Can another case label come after the default clause? Yes, you are allowed to place the default clause anywhere within the switch block.
3,003,317
3,003,331
C++, what does this syntax mean?
i found this in this file: http://www.boost.org/doc/libs/1_43_0/boost/spirit/home/phoenix/core/actor.hpp What does this syntax means? struct actor ... { ... template <typename T0, typename T1> typename result<actor(T0&,T1&)>::type // this line I know what typename and templates are, my question...
So this means that there is a template called result and within result is a type called type. template <class T> class result { public: typedef ... type; }; So that line is using that type from the template. Because the compiler does not know what result<actor(T0&,T1&)>::type is, you need to use typename to tell t...
3,003,521
3,003,552
Why is this C or C++ macro not expanded by the preprocessor?
Can someone points me the problem in the code when compiled with gcc 4.1.0. #define X 10 int main() { double a = 1e-X; return 0; } I am getting error:Exponent has no digits. When I replace X with 10, it works fine. Also I checked with g++ -E command to see the file with preprocessors applied, it has not replaced X...
When you write 1e-X all together like that, the X isn't a separate symbol for the preprocessor to replace - there needs to be whitespace (or certain other symbols) on either side. Think about it a little and you'll realize why.. :) Edit: "12-X" is valid because it gets parsed as "12", "-", "X" which are three separate ...
3,003,574
3,003,600
Explicit initialization of struct/class members
struct some_struct{ int a; }; some_struct n = {}; n.a will be 0 after this; I know this braces form of initialization is inherited from C and is supported for compatibility with C programs, but this only compiles with C++, not with the C compiler. I'm using Visual C++ 2005. In C this type of initialization struct ...
The empty braces form of initialization is standard in C++ (it's permitted explicitly by the grammar). See C Static Array Initialization - how verbose do I need to be? for more details if you're interested. I assume that it was added to C++ because it might not be appropriate for a 0 value to be used for a default init...
3,003,794
3,004,187
What event (if any) does QTextEdit fire when the size of its content changes?
As the title says, how can I receive notification whenever a multi-line QTextEdit changes the size of its content? (Note: content size is different from the control size, i.e. I want to know when lines were added or removed, or changed height because of a font change).
QTextEdit has a textChanged() signal which will do what you want. From the docs: "This signal is emitted whenever the document's content changes; for example, when text is inserted or deleted, or when formatting is applied." I wasn't sure if formatting included font changes but I tested it and it does.
3,003,810
3,004,249
How to get the volume GUID
I am using win32 api with C++. I would like to know how I can get the volume GUID using a "device path". My device looks like this: \\?\usb#vid_04f2&pid_0111#5&39fe81e&0&2#{a5dcbf10-6530-11d2-901f-00c04fb951ed} Thanks.
This will be the device with device instance ID usb\VID_04f2&PID_0111\5&39fe81e&0&2. That's probably a mass storage device aka disk. Now, the problem you have is that a mass storage device doesn't actually have a drive letter; it's the volume on that disk which has a drive letter. If there are two partitions, a single ...
3,003,891
3,005,381
How to process signals in a Qt subclass?
How do I process a signal of in a subclass? Let's say my subclass is derived from QTextEdit and is interested in the signal textChanged. It seems silly to connect an object to itself, I should be able to simply override the textChange method -- but it isn't virtual. What is the accepted way to do this?
You can't implement/override a signal, so the only way is to create a new slot and connect it to textChanged(): connect( this, SIGNAL(textChanged(QString)), this, SLOT(slotTextChanged(QString)) );
3,004,001
3,004,022
Any real use case for using the calling convention fastcall?
Have you had any real use case for using the calling convention fastcall? Thanks.
Here's an article explaining when to use fastcall. It actually specifies a case when you actually have no alternative but to use it: Some VCL classes, such as TList, allow you to specify a callback function (a sort routine in the case of TList). You will have to use the __fastcall keyword in this case, too, as...
3,004,040
3,004,048
What is a good idea for a list of strings?
I simply want to build an RPG and make it as neat as possible, I wish to define a pile of strings which I may want to edit later, so I tried something like this: enum { MSG_INIT = "Welcome to ...", MSG_FOO = "bar" }; But I just get errors, such as that MSG_INIT is not an integer! Why must it not be a string, are that ...
enums are for groups of related numeric constants that you want to manipulate efficiently in memory. Instead, you can just use C string constants: char const *const MSG_INIT = "Welcome to ..."; char const *const MSG_FOO = "bar"; You can make them public fields if you choose. E.g. struct SomeClass { static char co...
3,004,095
3,004,122
Division by zero: Undefined Behavior or Implementation Defined in C and/or C++?
Regarding division by zero, the standards say: C99 6.5.5p5 - The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined. C++03 5.6.4 - The bin...
I don't see any contradiction. Division by zero is undefined, period. There is no mention of "... unless INFINITY is defined" anywhere in the quoted text. Note that nowhere in mathematics it is defined that 1 / 0 = infinity. One might interpret it that way, but it is a personal, "shortcut" style interpretation, rather ...
3,004,311
3,004,366
How to read the whole istream correctly?
Here is a simple code to print all characters of a txt file on screen: #include <iostream> #include <fstream> #include <string> using namespace std; int main() { int **i; int j,k; char a; ifstream test("test.txt", ios::binary); while((a=test.get())!=-1)//if I use "while(!test.eof())" here,...
You want: int a; The get() function returns an int, not a char - this is the same in C - when using getchar(), you read into an int variable not char. So your loop looks like: while( ( a = test.get() ) != EOF ) note you want EOF here, not eof(). a version using eof() would look like this: char c; while( test.get( c...
3,004,501
3,004,555
Why do we need a virtual table?
I was looking for some information about virtual tables, but I can't find anything that is easy to understand. Can somebody give me good examples with explanations?
Without virtual tables you wouldn't be able to make runtime polymorphism work since all references to functions would be bound at compile time. A simple example struct Base { virtual void f() { } }; struct Derived : public Base { virtual void f() { } }; void callF( Base *o ) { o->f(); } int main() { Derived ...
3,004,796
3,004,840
C++ Using a class template argument as a template argument for another type
I'm having this problem while writing my own HashTable. It all works, but when I try to templatize the thing, it gave me errors. I recreated the problem as follows: THIS CODE WORKS: typedef double Item; class A { public: A() { v.push_back(pair<string, Item>("hey", 5.0)); } void iterate() ...
This is called "dependent names" in C++. In your second code snippet, you say: typedef vector< pair<string, ValueType> >::iterator Iterator; whereas you should say: typedef typename vector< pair<string, ValueType> >::iterator Iterator; Whenever you see an error saying "is not derived...", typename is to the rescue. I...
3,004,850
3,004,904
Portable way of counting milliseconds in C++?
Is there any portable (Windows & Linux) way of counting how many milliseconds elapsed between two calls ? Basically, I want to achieve the same functionnality than the StopWatch class of .NET. (for those who already used it) In a perfect world, I would have used boost::date_time but that's not an option here due to som...
On Linux (and generally in POSIX), you can use gettimeofday function, which returns number of microseconds since the Epoch. On Windows, there is GetTickCount function, that return number of milliseconds since the system was started.
3,004,870
3,012,678
Can a custom MFC window/dialog be a class template instantiation?
There's a bunch of special macros that MFC uses when creating dialogs, and in my quick tests I'm getting weird errors trying to compile a template dialog class. Is this likely to be a big pain to achieve? Here's what I tried: MyDlg.h template <class W> class CMyDlg : public CDialog { typedef CDialog super; DECL...
Here's a working solution, though ugly... I didn't get round to rewriting as a macro after expanding the existing one and fixing for templates: //Template-enabled expansion of IMPLEMENT_DYNAMIC(CMyDlg,super) template <class W> CRuntimeClass* PASCAL CMyDlg<W>::_GetBaseClass(){ return RUNTIME_CLASS(super); } template <cl...
3,004,889
3,005,400
GetVolumeNameForVolumeMountPoint returns false
To get the volume GUID i tried the code like below int len = wcslen( pDetData->DevicePath); pDetData->DevicePath[len] = '\\'; pDetData->DevicePath[len+1] = 0; #define BUFFER_SIZE MAX_PATH WCHAR volume[BUFFER_SIZE]; BOOL bFlag; bFlag = GetVolumeNameForVolumeMountPoint( pDetData->DevicePath, volume, BUFFER_SIZE ); int ...
This requires some crystal-ball consulting. The DevicePath string looks like it comes from SP_DEVICE_INTERFACE_DETAIL_DATA. That's a string that you don't own, modifying it corrupts the internal setupapi database at best, the heap at worst. You'll have to copy the string into your own buffer before turning it into t...
3,004,907
3,005,634
How can I login linux using C or C++
I need to programmely switch the current user to another,then the followed code should be executed in the environment(such as path,authority..) of another user. I've find the 'chroot()','setuid()' may be associated with my case, but these functions need the root authority, I don't have root authority, but I have the p...
when clients connect to the server, the server transfer the data what they need,but the precondition is the correct username and password. If your primary requirement is to authenticate, then try man pam. There are also some libraries allowing to auth over LDAP. Unfortunately I have no personal experience imple...
3,004,915
3,026,808
Getting hardware floating point with android NDK
I've begun playing with the android NDK. One of the things I've just learnt is about creating an application.mk file to specify the armv7 abi. I'm building the san-angeles example with the following parameters. APP_MODULES := sanangeles APP_PROJECT_PATH := $(call my-dir)/../ APP_OPTIM := release APP_ABI...
The options you supply to the NDK will only affect the way your code is compiled. It won't change the GL libs or anything else that's part of the platform, which are always generated in an appropriate fashion. If you're just throwing geometry at the GL hardware, you're not going to see a difference. If you want to se...
3,004,963
3,005,013
Counting of objects created in stack and heap for many classes
What is the best way to count the total number of objects created in both stack and heap for different classes. I know that in C++ new and delete operators can be overloaded and hence in the default constructor and destructor the object count can be incremented or decremented as and when the objects get created or dest...
then i can create a dummy class and write the object count code in that class and then when i create any new class i can derive it from the Dummy class. Yes, but since each class needs its own count, you have to make a base class template and use the curiously recurring template pattern (CRTP): template <class Derive...
3,004,979
3,005,225
C or C++: how do loaders/wrappers work?
Here's an example of what I mean... User runs LOADER.EXE program LOADER.EXE downloads another EXE but keeps it all in memory without saving it to disk Runs the downloaded EXE just as it would if it were executed from disk, but does it straight from memory I've seen a few applications like this, and I've never seen an...
A lot of programs that do this just unzip to %TEMP% (I know I do), but the big boys essentially re-implement the OS executable loader, which has to: Map the executable into memory. This is not as simple as it sounds, as the .exe contains multiple 'sections', which must be loaded with page alignment (they must start at...
3,005,059
3,005,371
Throwing Exception in CTOR and Smart Pointers
Is it OK to have the following code in my constructor to load an XML document into a member variable - throwing to caller if there are any problems: MSXML2::IXMLDOMDocumentPtr m_docPtr; //member Configuration() { try { HRESULT hr = m_docPtr.CreateInstance(__uuidof(MSXML2::DOMD...
C++ guarantees that in case of an exception all fully constructed objects will be destroyed. Since m_docPtr is a member of class Configuration it will have been fully constructed before the class Configuration constructor body begins, so if you throw an exception from class Configuration body as you intended in your fi...
3,005,171
3,005,232
Receive many datagrams from several hosts using winsock
I am developing an application that distributes rendering across several devices (a university project). Each frame consists of several blocks (16x16 pixels), and each device is "assigned" a number of blocks to be rendered. These blocks, when rendered, are compressed and serialized into a buffer until the max size of t...
That is probably not the cause of any perceived performance issue you are trying to address. Without seeing your code, I'll take a guess that what you're doing is: 1. recv a packet 2. Process a packet 3. repeat What you should be doing is: 1. use one thread to recv packets with a pool of buffers and shove the rec...
3,005,183
3,005,223
Windows DDK development with MinGW?
Is it possible to develop a Windows driver (specifically a PDF-like printer driver that displays the data on-screen instead of actually printing) without using Visual Studio? I'm thinking of using free C++ tools such as MinGW/gcc.
Both the Windows SDK and the Windows DDK come with the Visual C++ compiler. You don't need Visual Studio for this, though you may have some success with the free Express editions. I'd prefer this over MinGW anytime.
3,005,269
3,005,284
How can I concatenate two C++ maps
How can I concatenate the following two maps? map<string, map<string,string>> map1; map<string, map<string,string>> map2; I just want to add map2 to map1 and keep all elements already in map1, i.e., add map2 at the end of map1. I've tried map1.insert(map2.begin(), map2.end()), but it does not work since it overwrites ...
The question contradicts with the concept of a map. If you insert a value in a map, you expect it to be at 'the proper place', depending on it's key. This implies there is only one entry for each key. Instead, you could use a vector< pair< mymap::key, myamap::value > > and fill it with the entries of the first resp. ...
3,005,527
3,005,581
Return an array of a known size in C++?
If I can pass in an array of a known size: void fn(int(*intArray)[4]) { (*intArray)[0] = 7; } why can't I return one: int intArray[4] = {0}; int(*)[4] fn() { return &intArray; } here, the ")" in "(*)" generates "syntax error : )".
The [4] goes after the function name, just like it goes after the variable name in a variable definition: int (*fn())[4] { return &intArray; } Since this is very obscure syntax, prone to be confusing to everybody who reads it, I would recommend to return the array as a simple int*, if you don't have any special re...
3,005,564
3,005,673
GCC recommendations and options for fastest code
I'm distributing a C++ program with a makefile for the Unix version, and I'm wondering what compiler options I should use to get the fastest possible code (it falls into the category of programs that can use all the computing power they can get and still come back for more), given that I don't know in advance what hard...
Without knowing any specifics on your program it's hard to say. O3 covers most of the optimisations. The remaining options come "at a cost". If you can tolerate some random rounding and your code isn't dependent on IEEE floating point standards then you can try -Ofast. This disregards standards compliance and can gi...
3,005,717
3,005,771
Getting value of LSB from Hex (C code)
I've got a code like this in C: unsigned char const data[ ] = {0x0a, 0x1d, 0xf0, 0x07}; I need to extract it such that the final value is: 0xa1df7 I have only been able to extract and get it working if the hex values that have at least 1 zero: unsigned char const data[ ] = {0x0a, 0xd0, 0xf0, 0x07}; using the code be...
#include <stdio.h> #include <stdlib.h> unsigned char const data[ ] = {0x0a, 0x1d, 0xf0, 0x07}; int main(int argc, char*argv[]){ int i,r = 0; for(i=0; i<sizeof(data); i++){ if(data[i] & 0xf0) r = (r<<4) + (data[i]>>4); if(data[i] & 0x0f) r = (r<<4) + (data[i]&0x0f); } printf("%x\n",r); ...
3,005,975
3,006,047
ld returned 1 exit status
This is the code that i'm trying to run: #include <QApplication> #include <QPushButton> int main(int argc,char *argv[]) { QApplication app(argc,argv); return app.exec(); } And this is the error that i'm getting: :-1: error: collect2: ld returned 1 exit status
If you read the error message carefully, you will see the problem. ...ld.exe: cannot open output file ... The linker is trying to write the generated executable file (debug.exe) to disk, but is not allowed to (Permission denied). This is mostly due to the fact that the application you built is currently running. Clos...
3,006,158
3,010,559
Resources in static library question
This isn't a duplicate of VC++ resources in a static library because it didn't help :) I have a static library with TWO .rc files in it's project. When I build my project using the Debug configuration, I retrieve the following error (MSVS2008): fatal error LNK1241: resource file res_yyy.res already specified Note, tha...
Solved this problem by setting EXACTLY ONE .res output file in the settings. I'm not actually sure why it was ok in Release mode though.
3,006,259
4,238,857
What time function do I need to use with pthread_cond_timedwait?
The pthread_cond_timedwait function needs an absolute time in a time timespec structure. What time function I'm suppose to use to obtain the absolute time. I saw a lot of example on the web and I found almost all time function used. (ftime, clock, gettimeofday, clock_gettime (with all possible CLOCK_...). The pthread_c...
The function to use is clock_gettime() with the clock id of the condition variable. This clock id is CLOCK_REALTIME by default but can be changed (such as to CLOCK_MONOTONIC) by initializing the condition variable with a pthread_condattr_t on which pthread_condattr_setclock() has been called. Using time() is not a good...
3,006,413
3,006,486
Implementing operator< in C++
I have a class with a few numeric fields such as: class Class1 { int a; int b; int c; public: // constructor and so on... bool operator<(const Class1& other) const; }; I need to use objects of this class as a key in an std::map. I therefore implement operator<. What is the simplest implementation o...
It depends on if the ordering is important to you in any way. If not, you could just do this: bool operator<(const Class1& other) const { if(a == other.a) { if(b == other.b) { return c < other.c; } else { return b < other.b; } ...
3,006,438
10,466,773
Is there an online name demangler for C++?
I'm getting a fairly long and confusing link error, and would love it if I could just paste it into some textbox on some website and have the names un-mangled for me. Does anyone know of such a service?
I have created such an online serivice: https://demangler.com This is a gcc c++ symbol demangler. You just copy a stack trace, or the output of nm into a text box, and it will return the output with the names demangled. @Update: It now demangles MSVC and Java symbols also.
3,006,559
3,010,649
IOCTL_MOUNTMGR_QUERY_POINTS
when i include #include to use the IOCTL_MOUNTMGR_QUERY_POINTS i get the below error fatal error C1083: Cannot open include file: Mountmgr.h: No such file or directory How can i solve this error. Please guide me
If you need only IOCTL_MOUNTMGR_QUERY_POINTS definition it is following: #define MOUNTMGRCONTROLTYPE 0x0000006D // 'm' #define IOCTL_MOUNTMGR_QUERY_POINTS CTL_CODE(MOUNTMGRCONTROLTYPE, 2, METHOD_BUFFERED, FILE_ANY_ACCESS) all other constants are defined in WinIoCtl.h file which you find in Windows SDK instal...
3,006,650
3,006,680
Expected class name before ',' or ';'
I am getting an "Expected class-name before , or ; and I dont quite get how to fix it. Here is where the error is: class FXHost : public CPLAT::CP_Application, public CPLAT::CP_M_Listener { The file is FXHost.h and CPLAT:: is obviously a namespace where CP_Application and CP_M_Listener are. I dont see why this woul...
It looks like the compiler hasn't seen the class declaration for the two parent classes. The first thing I would check are your include directives. Are you sure you're including header which defines the classes CP_Application and CP_M_Listener?
3,006,690
3,007,306
keyboard layout direction
I would like to detect the direction of the current typing (input) language. I may detect the language by means of "GetKeyboardLayout", but then I'll have to check if it equals to Arabic or Hebrew and so on, is there any way just to detect the direction, i.e. left to right or right to left. thanks! mike.
check out: http://www.siao2.com/2006/03/03/542963.aspx
3,006,766
3,006,806
How to use the vtable to determine class type
I was recently on an interview for a position where C/C++ is the primary language and during one question I was told that it's possible to use the vtable to determine which class in a hierarchy a base pointer actually stores. So if, for example you have class A { public: A() {} virtual ~A(...
This is obviously implementation dependent but, on most implementations, the in-memory representation of an object of class A or B will start with a pointer to the vtable. You can look at this vtable pointer, compare it to vtable pointers for objects that you know to be of class A or B, and determine the class of the o...
3,006,815
3,013,342
Most efficient way to map one fileID to another
I am in the process of localizing a game. I have roughly 1% of the game assets (around 200 of 20k files) that need to be replaced per language with different assets, 1 to 1. I am mulling over the 'best' way to do this in a very RAM starved envirnoment. Here's my current list of ideas: Hash off the file IDs to conve...
You can pre-calculate the FileIDs that you need to convert. Look up perfect hashes; this may be what you need. However, 2log(200) is only 8. The overhead of hashing is significant, even more so for perfect hashing. And remember that files are slow - 8 memory accesses for a binary search will take perhaps a microsecond...
3,006,918
3,013,318
Is it safe to read global data from multiple threads?
The scenario is as follows: Create an instance of a class (std::map) and sore it as global variable. Spawn threads. Threads read and use the same global instance of the class (call methods, access members etc) All spawned threads quit Global class instance is destroyed No mutex used, no spawn thread modifies the glob...
Typically yes, but it's not a hard guarantee. The core problem is that you need a memory barrier to make sure that the first thread writes back all data from registers to memory. However, it is very likely that this will happen when you create the second thread.
3,007,250
3,007,266
Should I use Qt signal/slot mechanisms over traditional callbacks?
A senior developer in my team used traditional C-style callbacks in our Qt application instead of using Qt signal/slot mechanisms. My first reflex would be to replace his code and use Qt signal/slot instead. Is there any good reasons to use callbacks in a Qt application/library? Thanks.
I think the better approach would be to embrace the framework you are using and use signal/slots. That being said, if the code in question works, and is not ugly or causing problems, then you may be best to leave it alone. Consulting the Signal/Slot documentation describes why the Signal/Slot approach is better: Call...
3,007,251
3,007,677
Template operator linker error
I have a linker error I've reduced to a simple example. The build output is: debug/main.o: In function main': C:\Users\Dani\Documents\Projects\Test1/main.cpp:5: undefined reference tolog& log::operator<< (char const (&) [6])' collect2: ld returned 1 exit status It looks like the linker ignores the definit...
I guess this is your first use of templates, so I'll try to be didactic. You can think of template as some kind of type-aware macros. This type awareness is of course not to be neglected, since it grants type safety for free. This does mean however than template functions or classes are NOT functions or classes: they a...
3,007,393
3,007,421
which is better: a lying copy constructor or a non-standard one?
I have a C++ class that contains a non-copyable handle. The class, however, must have a copy constructor. So, I've implemented one that transfers ownership of the handle to the new object (as below), class Foo { public: Foo() : h_( INVALID_HANDLE_VALUE ) { }; // transfer the handle to the new instance ...
The first option has a well established precedent in the form of auto_ptr: http://www.cplusplus.com/reference/std/memory/auto_ptr/auto_ptr/ auto_ptr gives up its pointer and is reset when it is copied. The standard that ensures that a function doesn't change arguments passed as const is much stronger than the copy-ctor...
3,007,422
3,007,890
How to optimize this simple function which translates input bits into words?
I have written a function which reads an input buffer of bytes and produces an output buffer of words where every word can be either 0x0081 for each ON bit of the input buffer or 0x007F for each OFF bit. The length of the input buffer is given. Both arrays have enough physical place. I also have about 2Kbyte free RAM w...
I also have about 2Kbyte free RAM which I can use for lookup tables Your lookup tables can placed in a const array at compile time, so it could be in ROM - does this give you room for the straightforward 4KB table? If you can afford 4KB of ROM space, the only problem is building the table as an initialized array in...
3,007,559
3,008,262
How to set the correct Visual Studio version as JIT debugger?
I have VS2003, VS2005 and VS2008 installed on my machine. The C++ application is compiled with VS2005 but when it crashs and i select debug the Just-In-Time Debugging dialog comes up and only offers me "New instance of Visual Studio .NET 2003". Debugging a 2005 compiled program with 2003 is not possible. If i attach...
Okay i found it. BTW installing VS2003 after VS2005 kills all others JIT debuggers, this was the reason for the problem. From Visual Studio menu , select "Tools->Options->Debugging->Just-In-Time" and then check "Managed", "Native" and "Script".
3,007,724
3,008,304
Determining CPU usage in WinCE
I want to be able to get the current % CPU usage in a C++ program running under Wince. I found this link that states where the source code is but I cannot find it in my platform builder installation - I expect this is because it isn't the Windows Automotive platform. Does anyone know where I can find this source code o...
Since GetProcessTimes doesn't exist in CE, you have to calculate this. You have to start with the toolhelp APIs to enumerate the processes and the threads in the processes. You then call GetThreadTimes for each thread and add all that up. Bear in mind that the act of calculating this info will affect the CPU utiliza...
3,007,728
3,025,835
rvalues and temporary objects in the FCD
It took me quite some time to understand the difference between an rvalue and a temporary object. But now the final committee draft states on page 75: An rvalue [...] is an xvalue, a temporary object or subobject thereof, or a value that is not associated with an object. I can't believe my eyes. This must be an error...
Yes, i agree with you. This should be fixed in my opinion, and several people i deeply pay respect to have risen the exact same question about this.
3,007,971
3,009,812
SQLite problem with some parameterized queries
I am having some trouble using SQLite and parameterized queries with a few tables. I have noticed some queries using the SELECT * FROM Table WHERE row=? are returning 1 row when there should be more rows returned. If I change the parameterized query to SELECT * FROM Table WHERE row='row' then the correct number of ro...
I have solved the problem. This code is running on Windows CE/Windows Mobile platform where virtually all system API are Unicode-only. I am using the ATL 7.0 conversion utility CT2A to convert between T (Unicode) to A (Ascii) before passing the variable to SQLite via the sqlite3_bind_xxx functions. This appears to b...
3,008,002
3,008,031
Access specifier's and classes and objects?
Alright, im trying to understand this, so a class is simply creating a template for an object. class Bow { int arrows; }; and an object is simply creating a specific item using the class template. Bow::Bow(arrows) { arrows = 20; } also another question, public specifiers are used to make data members avaible in ob...
The description you gave is mostly correct but your examples don't show what you are describing. A class describes a set of data members and member functions which can be called on those data members: class Bow { public: //Constructor Bow::Bow() { arrows = 20; } Bow::Bow(int a) { arrows =...
3,008,094
3,008,136
C++: vector to stringstream
I want to know if it is possible to transform a std::vector to a std::stringstream using generic programming and how can one accomplish such a thing?
Adapting Brian Neal's comment, the following will only work if the << operator is defined for the object in the std::vector (in this example, std::string). #include <iostream> #include <sstream> #include <vector> #include <string> #include <iterator> // Dummy std::vector of strings std::vector<std::string> sentence;...
3,008,270
3,008,428
Declaration for object for which creation is wrapped in macro
The following macro is defined in our code: #define MSGMacro(obj, arg) MyPaymentClass obj(arg) Where MSGMacro is used to creates the object of type MyPaymentClass using code like MSGMacro(Card, 1); MSGMacro(Cash, 2); ---- ---- //removed unwanted things to keep question cleaner. All the above code is in one cpp fi...
Create another macro to declare these variables: /* example.h */ #define MSGMacroDeclare(obj) extern MyPaymentClass obj; MSGMacroDeclare(Card); MSGMacroDeclare(Cash); ... /* example.cpp */ #define MSGMacroDefine(obj, arg) extern MyPaymentClass obj(arg); MSGMacroDefine(Card, 1); MSGMacroDefine(Cash, 2); ... Eventually...
3,008,293
3,008,319
Clean Eclipse Index, it is out of sync with code
I'm using Eclipse with C++ code via linked resources on Linux. The code analysis index seems to be corrupted (Goto definition lands the cursor close to, but not on, the definition) Refreshing resources doesn't fix it, neither does restarting Eclipse. Is there a way to flush the index and rebuild it?
Right-click on your project, go under the Index submenu, and choose either "Rebuild," "Update with modified files," or "Freshen all files." I don't know the difference between those three options, but one of "Update with modified files" or "Freshen all files" usually fixes it for me. Also, I'm sure you've already done ...
3,008,413
3,021,785
Conditional type definitions
I'm sure that boost has some functions for doing this, but I don't know the relevant libraries well enough. I have a template class, which is pretty basic, except for one twist where I need to define a conditional type. Here is the psuedo code for what I want struct PlaceHolder {}; template <typename T> class C{ ...
Also with the new standard: typedef typename std::conditional<std::is_same<T, PlaceHolder>::value, void, T>::type usefulType
3,008,521
3,008,905
How to safely operate on parameters in threads, using C++ & Pthreads?
I'm having some trouble with a program using pthreads, where occassional crashes occur, that could be related to how the threads operate on data So I have some basic questions about how to program using threads, and memory layout: Assume that a public class function performs some operations on some strings, and returns...
1 a/b: No, neither one can happen. The parameters to functions and their return values are located on the stack and each thread has his own stack. However, other things can certainly go wrong: one of the string operations could throw an exception, preventing someclasslock from ever getting unlocked and your applicati...
3,008,571
3,009,891
Template specialization to use default type if class member typedef does not exist
I'm trying to write code that uses a member typedef of a template argument, but want to supply a default type if the template argument does not have that typedef. A simplified example I've tried is this: struct DefaultType { DefaultType() { printf("Default "); } }; struct NonDefaultType { NonDefaultType() { p...
To answer your addition - your specialization argument passes the member typedef and expects it to yield void as type. There is nothing magic about this - it just uses a default argument. Let's see how it works. If you say Get_Type<Foo>::type, the compiler uses the default argument of Enable, which is void, and the typ...
3,008,690
3,008,730
User Defined Conversions in C++
Recently, I was browsing through my copy of the C++ Pocket Reference from O'Reilly Media, and I was surprised when I came across a brief section and example regarding user-defined conversion for user-defined types: #include <iostream> class account { private: double balance; public: account (...
Is this a particularly obscure feature? Yes, conversion operators aren't used very often. The places I've seen them are for user-defined types that can degrade to built-in ones. Things like a fixed-precision number class that supports converting to/from atomic number types. Is this relatively portable? As far as I ...
3,008,874
3,009,317
Reverse P/Invoke tutorial?
I've a old C/C++ class that i want to refactor and access from .net using PInvoke All P/Invoke tutorials refers to call win32 api but i haven't found anything to code the other side Any tips/ideas ? my c/c++ experience is pretty rusty :( UPDATE - this is for wrapping existing C/C++ code so it can called from .net using...
Here you find help C++ Interop Walkthrough: Porting an Existing Native C++ Application to Interoperate with .NET Framework Components Use Our ManWrap Library to Get the Best of .NET in Native C++ Code How to call C++ code from Managed, and vice versa (Interop)
3,008,878
3,008,996
Gradient algorithm produces little white dots
I'm working on an algorithm to generate point to point linear gradients. I have a rough proof of concept implementation done: GLuint OGLENGINEFUNCTIONS::CreateGradient( std::vector<ARGBCOLORF> &input,POINTFLOAT start, POINTFLOAT end, int width, int height,bool radial ) { std::vector<POINT> pol; std::vector<GLub...
I think you have a bug indexing into the pdata byte vector. Your x domain is [0, width) but when you multiply out the indices you're doing x * 4 * width. It should probably be x * 4 + y * 4 * width or x * 4 * height + y * 4 depending on whether you're data is arranged row or column major.
3,009,149
3,009,189
How to use a precompiled dynamic library in visual studio c++?
I want to use a precompiled library in my project. I have 3 folders: Include (.h files), Lib (with .lib files) and Bin (with .dll files and .pdb files). I've never used precompiled libraries before (I hope this is the right term. correct me if I'm wrong). I want to use this API. How to add all this stuff to my project?...
It's quite easy. You just need to modify some properties: C++ / General / Additional Include Directories - add the path where the .h file lives Linker / General / Additional Library Directoreis - add the path where the .lib file lives Linker / Input / Additional Dependencies - add the full name of the .lib When you ...
3,009,210
3,009,348
ebp + 6 instead of +8 in a JIT compiler
I'm implementing a simplistic JIT compiler in a VM I'm writing for fun (mostly to learn more about language design) and I'm getting some weird behavior, maybe someone can tell me why. First I define a JIT "prototype" both for C and C++: #ifdef __cplusplus typedef void* (*_JIT_METHOD) (...); #else typedef (*_JI...
Your opcodes look suspicious: they're full of 0x66 and 0x67 address/data size override prefixes, which (in a 32-bit code segment) will turn 32-bit operations into 16-bit ones. e.g. buffer[0] = 0x66; buffer[1] = 0x55; buffer[2] = 0x66; buffer[3] = 0x89; buffer[4] = 0xE5; ... is push bp mov bp, sp rather than push eb...
3,009,268
3,009,298
Clamping a vector to a minimum and maximum?
I came accross this: t = Clamp(t/d, 0, 1) but I'm not sure how to perform this operation on a vector. What are the steps to clamp a vector if one was writing their own vector implementation? Thanks clamp clamping a vector to a minimum and a maximum ex: pc = # the point you are coloring now p0 = # start point p1 ...
clamp(vec, lb, ub) == min(max(vec, lb), ub) edit min and max are usually primitive operations on vectors. For example, if you're using SSE vectors, there are _mm_min_ps and _mm_max_ps intrinsics that turn into MINPS and MAXPS instructions on x86.
3,009,355
3,009,772
Overwhelmed by design patterns... where to begin?
I am writing a simple prototype code to demonstrate & profile I/O schemes (HDF4, HDF5, HDF5 using parallel IO, NetCDF, etc.) for a physics code. Since focus is on IO, the rest of the program is very simple: class Grid { public: floatArray x,y,z; }; class MyModel { public: MyModel(const int &nip1, const int &njp1...
"Which pattern(s) would you recommend I use to integrate I/O with the myModel object?" You're asking the wrong question. The question you should be asking is, "How can I separate my model from I/O?" There's lots of answers. One interesting setup I've seen is Robert C. Martin's use of proxy. Your idea of using decora...
3,009,379
3,009,395
how to swap array-elements to transfer the array from a column-like into a row-like representation
For example: the array a1, a2, a3, b1, b2, b3, c1, c2, c3, d1, d2, d3 represents following table a1, b1, c1, d1 a2, b2, c2, d2 a3, b3, c3, d3 now i like to bring the array into following form a1, b1, c1, d1, a2, b2, c2, d2, a3, b3, c3, d3 Does an algorithm exist, which takes the array (from the first form) and the d...
The term you're looking for is in-place matrix transpose, and here's an implementation.
3,009,489
3,009,768
Creating an object in the loop
std::vector<double> C(4); for(int i = 0; i < 1000;++i) for(int j = 0; j < 2000; ++j) { C[0] = 1.0; C[1] = 1.0; C[2] = 1.0; C[3] = 1.0; } is much faster than for(int i = 0; i < 1000;++i) for(int j = 0; j < 2000; ++j) { std::vector<double> C(4); C[0] = 1.0; C[1] = 1.0; C[2] = 1.0;...
Is it completely wrong to keep variables local in a loop whenever possible? I was under the (perhaps false) impression that this would provide optimization opportunities for the compiler. No, that's a good rule of thumb. But it is only a rule of thumb. Minimizing the scope of a variable gives the compiler more free...
3,009,533
3,009,954
Boost.Python tutorial in Ubuntu 10.04
I downloaded the latest version of Boost and I'm trying to get the Boost.python tutorial up and running on Ubuntu 10.04: http://www.boost.org/doc/libs/1_43_0/libs/python/doc/tutorial/doc/html/python/hello.html I navigated to the correct directory, ran "bjam" and it compiled using default settings. I did not yet create ...
How did you install boost ? Assuming you have use the following: http://www.boost.org/doc/libs/1_43_0/more/getting_started/unix-variants.html#easy-build-and-install liboost_python shard library will be install in /usr/local/lib To run the hello.py example, try the following: LD_LIBRARY_PATH=/usr/local/lib python ./hell...
3,009,543
3,009,568
Passing integers as constant references versus copying
This might be a stupid question, but I notice that in a good number of APIs, a lot of method signatures that take integer parameters that aren't intended to be modified look like: void method(int x); rather than: void method(const int &x); To me, it looks like both of these would function exactly the same. (EDIT: appar...
It's not just the cost of passing a pointer (that's essentially what a reference is), but also the de-referencing in the called method's body to retrieve the underlying value. That's why passing an int by value will be virtually guaranteed to be faster (Also, the compiler can optimize and simply pass the int via proces...
3,009,676
3,010,297
connecting cell phone to computer
is it possible for me to intercept the text messages that get sent to my cellphone if i connect to my cellphone via bluetooth or USB or some other connection to my computer? i want to create a database with all of my received text messages and be able to control my cell phone through my computer by using it to send tex...
According to GSM Specification 27.005 you should be able to get indication on incoming sms. You need to open AT Command terminal to the phone (most of the times you do that by plugging the phone to the usb, and connect to the com port that was created for it). The command that you are looking for is AT+CNMI. Just read ...
3,009,699
3,009,746
How efficient is an if statement compared to a test that doesn't use an if? (C++)
I need a program to get the smaller of two numbers, and I'm wondering if using a standard "if x is less than y" int a, b, low; if (a < b) low = a; else low = b; is more or less efficient than this: int a, b, low; low = b + ((a - b) & ((a - b) >> 31)); (or the variation of putting int delta = a - b at the top and rerp...
(Disclaimer: the following deals with very low-level optimizations that are most often not necessary. If you keep reading, you waive your right to complain that computers are fast and there is never any reason to worry about this sort of thing.) One advantage of eliminating an if statement is that you avoid branch pre...
3,009,744
3,009,769
What is causing this template-related compile error?
When I try to compile this: #include <map> #include <string> template <class T> class ZUniquePool { typedef std::map< int, T* > ZObjectMap; ZObjectMap m_objects; public: T * Get( int id ) { ZObjectMap::const_iterator it = m_objects.find( id ); if( it == m_obj...
You need typename: typename ZObjectMap::const_iterator it = m_objects.find( id ) Since the type of ZObjectMap is dependent on the template parameter, the compiler has no clue what ZObjectMap::const_iterator is (it could be a member variable). You need to use typename to inform the compiler to assume it will be some s...
3,009,754
3,010,607
Algorithm to generate radial gradient
I have this algorithm here: pc = # the point you are coloring now p0 = # start point p1 = # end point v = p1 - p0 d = Length(v) v = Normalize(v) # or Scale(v, 1/d) v0 = pc - p0 t = Dot(v0, v) t = Clamp(t/d, 0, 1) color = (start_color * t) + (end_color * (1 - t)) to generate point to point linear gradients. It works...
Linerise over atan2(dy,dx) where dx is x-center, and dy is y-center. cx # center x cy # center y r1 # ring is defined by two radius r2 # r1 < r2 c1 # start color c2 # stop color ang # start angle px # currect point x,y py if( px^2 + py^2 <= r2^2 AND px^2 + py^2 >= r1^2 ) # lies in ring? t= atan2(py-cy,px-c...