question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
1,695,421
1,695,442
Creating spherical meshes with Direct x?
How do you go about creating a sphere with meshes in Direct-x? I'm using C++ and the program will be run on windows, only. Everything is currently rendered through an IDiRECT3DDEVICE9 object.
You could use the D3DXCreateSphere function.
1,695,474
1,695,485
Localization of string literals
I need to localize error messages from a compiler. As it stands, all error messages are spread throughout the source code as string literals in English. We want to translate these error messages into German. What would be the best way to approach this? Leave the string literals as-is, and map the char* to another language inside the error reporting routine, or replace the english literals with a descriptive macro, eg. ERR_UNDEFINED_LABEL_NAME and have this map to the correct string at compile time? How is such a thing approached in similar projects?
On Windows, typically this is done by replacing the string with integer constants, and then using LoadString or similar to get them from a resource in a DLL or EXE. Then you can have multiple language DLLs and a single EXE. On Unixy systems I believe the most typical approach is gettext. The end result is similar, but instead of defining integer constants, you wrap your English string literals in a macro, and it will apply some magic to turn that into a localized string.
1,695,681
1,695,690
Reading from and writing to the middle of a binary file in C/C++
If I have a large binary file (say it has 100,000,000 floats), is there a way in C (or C++) to open the file and read a specific float, without having to load the whole file into memory (i.e. how can I quickly find what the 62,821,214th float is)? A second question, is there a way to change that specific float in the file without having to rewrite the entire file? I'm envisioning functions like: float readFloatFromFile(const char* fileName, int idx) { FILE* f = fopen(fileName,"rb"); // What goes here? } void writeFloatToFile(const char* fileName, int idx, float f) { // How do I open the file? fopen can only append or start a new file, right? // What goes here? }
You know the size of a float is sizeof(float), so multiplication can get you to the correct position: FILE *f = fopen(fileName, "rb"); fseek(f, idx * sizeof(float), SEEK_SET); float result; fread(&result, sizeof(float), 1, f); Similarly, you can write to a specific position using this method.
1,695,777
1,695,850
Any tips for a newbie who wants to find a good debugger for C++?
I'm trying to debug my code. I haven't really used a debugger before. I know that in the long run, learning how to use a debugger will be very, very helpful, so I'm trying to find one that suits me. Are there any newbie-friendly debuggers for C++? Ideally with a good GUI... If not, can anyone point me to a good, newbie-friendly guide to using gdb? My prof recommended it, but it seems to have somewhat of a steep learning curve (at least, for me) since I don't know what to look out for and how to use it. I've tried googling, but I can't seem to find a decent guide. In short, I just want to set breakpoints and step through the code while checking the values that are being assigned into my variables. Also, being able to view my code while debugging would be awesome. If its of any importance, I'm running on a mac, and I have gdb installed. I use the NetBeans IDE to code with, and it debugs with gdb (I think), but I don't know how to use it. I have finally decided on trying out a debugger instead of spot-checking my code. I've spent too many hours pulling my hair out on my current programming project. (I'm trying to make an AVL Tree, for those of you who are interested :D) Thanks!
If you are having troubles with the UI of GDB, try DDD. It is a graphical front-end for debuggers like GDB, and has quite a number of nice features. You can see a sample session of it here.
1,695,807
1,696,194
Why isn't C/C++'s "#pragma once" an ISO standard?
I am currently working on a big project and maintaining all those include guards makes me crazy! Writing it by hand is frustrating waste of time. Although many editors can generate include guards this doesn't help much: Editor generates guard symbol based on a filename. The problem occurs when you have headers with the same filename in different directories. Both of them will get the same include guard. Including directory structure into the guard symbol would require some fancy approach from the editor, since slashes and backslashes in the macro are not the best thing. When I have to rename a file I should rename all the include guards as well (in the ifndef, define and ideally endif's comment). Annoying. Preprocessor is flooded with tons of symbols without a clue what they mean. Nevertheless definition is included once, compiler still opens header every time it meets header inclusion. Include guards don't fit into namespaces nor templates. In fact they are subverting namespaces! You have a chance that your guard symbol won't be unique. Maybe they were acceptable solution in times when programs contained less than 1000 headers in single directory. But nowadays? It is ancient, it has nothing to do with modern coding habits. What bothers me the most is that this issues could be almost compeletly solved by #pragma once directive. Why is it not a standard?
A directive like #pragma once is not trivial to define in a fully portable way that has clear an unambiguous benefits. Some of the concepts for which it raises questions are not well defined on all systems that support C, and defining it in a simple way might provide no benefit over conventional include guards. When the compile encounters #pragma once, how should it identify this file so that it doesn't include its contents again? The obvious answer is the unique location of the file on the system. This is fine if the system has unique locations for all files but many systems provide links (symlinks and hardlinks) that mean that a 'file' doesn't have a unique location. Should the file be re-included just because it was found via a different name? Probably not. But now there is a problem, how is it possible to define the behaviour of #pragma once in a way that has an exact meaning on all platforms - even those that don't even have directories, let alone symlinks - and still get the desirable behaviour on systems that do have them? You could say that a files identity is determined by its contents, so if an included file has a #pragma once and a file is included that has exactly the same contents, then the second and subsequent #includes shall have no effect. This is easy to define and has well defined semantics. It also has good properties such that if a project is moved from a system that supports and uses filesystem links to one that doesn't, it still behaves the same. On the downside, every time an include file is encountered containing a #pragma once its contents must be checked against every other file using #pragma once that has already been included so far. This implies a performance hit similar to using #include guards in any case and adds a not insignificant burden to compiler writers. Obviously, the results of this could be cached, but the same is true for conventional include guards. Conventional include guards force the programmer to choose a macro that is the unique identifier for an include file, but at least the behaviour is well-defined and simple to implement. Given the potential pitfalls and costs, and the fact the conventional include guards do work, it is not surprising to me that the standards committee didn't feel the need to standardize #pragma once.
1,695,922
1,695,939
Representing integers as a byte
Currently I'm working on an assignment and using C++ for the first time. I'm trying to append certain "message types" to the beginning of strings so when sent to the server/client it will deal with the strings depending on the message type. I was wondering if I would be able to put any two-digit integer into an element of the message buffer.... see below. I've left a section of the code below: char messageBuffer[32]; messageBuffer[0] = '10'; << I get an overflow here messageBuffer[1] = '0'; for (int i = 2; i < (userName.size() + 2); i++) { messageBuffer[i] = userName[(i - 2)]; } Thanks =)
'10' is not a valid value, thus the overflow either write 10 as in messageBuffer[0]=10 - if ten is the value you want to put it or do as Lars wrote.
1,696,009
1,696,038
Mysql_num_rows() Segfaults
I'm writing a program using C++ and the MySQL C API (version 5.1.31 ubuntu2). However, if the query is UPDATE then I get a Segmentation Fault error when executing the line "RowsReturned = mysql_num_rows( Result );". //this code snippet contains only the relevant code MYSQL_RES *Result; long RowsReturned; MYSQL_RES *MYSQLDB::RunQuery( const char* Query ) { if( mysql_query( Connection, Query) ) { std::cout << "Error: " << mysql_error( Connection ); exit(1); } Result = mysql_store_result( Connection ); RowsReturned = mysql_num_rows( Result ); return Result; } Compiled using g++ 4.3.3 (g++ test.cpp -I/usr/include/mysql -L/usr/lib/mysql -lmysqlclient_r -o Test) Thanks in advance. //this snippet contains the entire class code class MYSQLDB { public: void Connect( const char* DB ); MYSQL_RES *RunQuery( const char* Query ); long NumRows(); void Close(); MYSQL_ROW GetRow(); private: MYSQL *Connection; MYSQL_RES *Result; MYSQL_ROW Row; long RowsReturned; }; void MYSQLDB::Connect( const char* DB ) { Connection = mysql_init( NULL ); if( Connection == NULL ) { std::cout << "Error: " << mysql_error( Connection ); exit( 1 ); } if ( mysql_real_connect( Connection, "localhost", "root", "password", DB, 0, NULL, 0 ) == NULL) { std::cout << "Error: " << mysql_error( Connection ); exit(1); } } MYSQL_RES *MYSQLDB::RunQuery( const char* Query ) { if( mysql_query( Connection, Query) ) { std::cout << "Error: " << mysql_error( Connection ); exit(1); } Result = mysql_store_result( Connection ); RowsReturned = (long)mysql_num_rows( Result ); //ERROR!!!!!!! return Result; } long MYSQLDB::NumRows() { return RowsReturned; } void MYSQLDB::Close() { mysql_free_result( Result ); mysql_close( Connection ); } MYSQL_ROW MYSQLDB::GetRow() { return mysql_fetch_row( Result ); }
From the mysql documentation: mysql_store_result() returns a null pointer if the statement didn't return a result set (for example, if it was an INSERT statement). You are updating so you have a NULL as results. Try something like this: Result = mysql_store_result( Connection ); if (Result) { RowsReturned = mysql_num_rows( Result ); } else { RowsReturned = 0; }
1,696,086
1,696,174
What's the best way to get the length of the decimal representation of an int in C++?
What's the best way to write int NumDigits(int n); in C++ which would return the number of digits in the decimal representation of the input. For example 11->2, 999->3, -1->2 etc etc.
Straightforward and simple, and independent of sizeof(int): int NumDigits(int n) { int digits = 0; if (n <= 0) { n = -n; ++digits; } while (n) { n /= 10; ++digits; } return digits; }
1,696,225
1,696,249
Null Pointer to Object problems
Hi can someone tell why in Linux and windows the same problem occurs : #include <iostream> using namespace std; class A { private: int _dmember; public: void func() { cout<<"Inside A!! "<<endl; cout<<_dmember; // crash when reach here. } }; int main () { A* a= NULL; a->func(); // prints "Inside A!!!" return 1; } can someone tell why this weird behivior occurs ? i mean , the a->func() was not supposed to get inside the func() ,...? this is unwated behavior , why the above behivor occurs? EDIT: Of course , a* =null was intentionaly!! so for all who answered "this is undefined behavior" or "you should never try to call a function on a NULL pointer !!", come on.... that was the point. and this behavior was explained correctly by some of you.
This is undefined behaviour. You must never call functions on a null pointer. With that out of the way, let's answer the question I think you're asking: why do we get partway into the function anyway? When you are invoking UB, the compiler is free to do anything, so it's allowed to emit code that works anyway. That's what happens on some (many?) systems in this particular case. The reason that you're able to call the function on a null pointer successfully is that your compilers don't store the function "in" the object. Rather, the above code is interpreted somewhat like this: class A { int _dmember; }; void A::func(A *this) { cout << "Inside A!!" << endl; cout << this->_dmember << endl; } int main() { A *a = ...; A::func(a); } So, you see there is nothing that actually prevents you from calling a function on a null pointer; it'll just invoke the body of the function, with the this pointer set to null. But as soon as the function tries to dereference the this pointer by accessing a field inside the class, the operating system steps in and kills your program for illegal memory access (called segmentation fault on Linux, access violation on Windows). Nitpicker's corner: Virtual functions are a different story.
1,696,300
1,696,309
How to compile C++ under Ubuntu Linux?
I cut&pasted the below code from a previous question into a file called "avishay.cpp" and then ran gcc avishay.cpp only to get the following error messages from the linker. What went wrong, what should I have done? carl@carl-ubuntu:~/Projects/StackOverflow$ gcc -static avishay.cpp /tmp/cccRNW34.o: In function `__static_initialization_and_destruction_0(int, int)': avishay.cpp:(.text+0x41): undefined reference to `std::ios_base::Init::Init()' avishay.cpp:(.text+0x46): undefined reference to `std::ios_base::Init::~Init()' /tmp/cccRNW34.o: In function `A::func()': avishay.cpp:(.text._ZN1A4funcEv[A::func()]+0x11): undefined reference to `std::cout' avishay.cpp:(.text._ZN1A4funcEv[A::func()]+0x16): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)' avishay.cpp:(.text._ZN1A4funcEv[A::func()]+0x1e): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)' avishay.cpp:(.text._ZN1A4funcEv[A::func()]+0x26): undefined reference to `std::basic_ostream<char, std::char_traits<char> >::operator<<(std::basic_ostream<char, std::char_traits<char> >& (*)(std::basic_ostream<char, std::char_traits<char> >&))' avishay.cpp:(.text._ZN1A4funcEv[A::func()]+0x36): undefined reference to `std::cout' avishay.cpp:(.text._ZN1A4funcEv[A::func()]+0x3b): undefined reference to `std::basic_ostream<char, std::char_traits<char> >::operator<<(int)' /tmp/cccRNW34.o:(.eh_frame+0x12): undefined reference to `__gxx_personality_v0' collect2: ld returned 1 exit status The C++ code (not my code, I was just trying to run it): #include <iostream> using namespace std; class A { private: int _dmember; public: void func() { cout<<"Inside A!! "<<endl; cout<<_dmember; // crash when reach here. } }; int main () { A* a= NULL; a->func(); // prints "Inside A!!!" return 1; }
You should use g++, not gcc, to compile C++ programs. For this particular program, I just typed make avishay and let make figure out the rest. Gives your executable a decent name, too, instead of a.out.
1,696,671
1,696,720
How to detect programmatically count of bytes allocated by process on Heap?
How to detect programmatically count of bytes allocated by process on Heap? This test should work from process itself.
A speculative solution: redefine new and delete operators. On each new operator call, a number of bytes to allocate is passed. Allocate a bit more memory and store the amount of bytes allocated within. Add this amount to global variable that holds the heap size. On delete operator call, check the value you stored before you dispose the memory. Subtract it from that global variable.
1,696,683
1,696,721
Explicitly rounding numbers to more than 7 decimal places in C++
Here is my code: double round( char* strNumber, int decPlace); int main() { int decimal; char initialNumber[256]; cout << "Enter decimal and number " << endl; cin >> decimal; cin >> initialNumber; cout << setprecision (15) << round ( initialNumber,decimal ) << endl; return 0; } double round( char* strNumber, int decPlace)// { double number = atof(strNumber); int temp = ( int ) ( pow(10.0,decPlace) * number + 0.5 ); double result = ( double ) temp / pow(10.0,decPlace); return result; } It works up to 6 decimal places. Otherwise it gives some strange result. Below are numbers that I used for testing and the output: Test 1-round to 7 decimal places 105.265 52.5689745694 25.6835 452.689785 12.456789877458 Output 105.265 52.5689746 25.6835 -214.7483648 12.4567899 Test 1-round to 8 decimal places The same numbers as previously Output -21.47483648 -21.47483648 -21.47483648 -21.47483648 12.45678988
As others have said, the cast to int won't work with large numbers. You could consider using floor instead, and keeping the number to be rounded in a double: #include <cstdlib> #include <cmath> double round( char* strNumber, int decPlace) { double number = std::atof(strNumber); double expo = std::pow(10.0,decPlace); return std::floor( expo * number + 0.5) / expo; }
1,696,769
1,696,875
Force showing system tray notification balloons
My application (C++ WinAPI) creates an icon in the system tray. I have set a tooltip text for this icon, so that when a user places a mouse cursor over the icon, this text shows. But I want to programmatically show different balloon notications when certan events occur and at the same time keep that behavior of showing the constant notification message when a user places a mouse over the icon. How to achieve this in C++ WinAPI? Thanks Alexander Smirnov
You can add the balloon using the .szInfo (message) and .szInfoTitle (title) members of the NOTIFYICONDATA structure that you send to Shell_NotifyIcon(). The mouse-over tooltip text is set in .szTip so this is independent of the balloon - as long as you keep .szTip to the tooltip you want you can do as much NIM_MODIFY calls to change the balloon while not changing anything to the tooltip.
1,697,153
1,697,202
Which database should I use to store records, and how should I use it?
I'm developing an application that will store a sizeable number of records. These records will be something like (URL, date, title, source, {optional data...}) As this is a client-side app, I don't want to use a database server, I just want the info stored into files. I want the files to be readable from various languages (at least python and C++), so something language specific like python's pickle is out of the game. I am seeing two possibilities: sqlite and BerkeleyDB. As my use case is clearly not relational, I am tempted to go with BerkeleyDB, however I don't really know how I should use it to store my records, as it only stores key/value pairs. Is my reasoning correct? If so, how should I use BDB to store my records? Can you link me to relevant info? Or am I missing a better solution?
I am seeing two possibilities: sqlite and BerkeleyDB. As my use case is clearly not relational, I am tempted to go with BerkeleyDB, however I don't really know how I should use it to store my records, as it only stores key/value pairs. What you are describing is exactly what relational is about, even if you only need one table. SQLite will probably make this very easy to do. EDIT: The relational model doesn't have anything to do with relationships between tables. A relation is a subset of the Cartesian product of other sets. For instance, the cartesian product of the Real numbers, Real Numbers, and Real numbers (Yes, all three the same) produce 3d coordinate space, and you could define a relation upon that space with a formula, say x*y = z. each possible set of coordinates (x0,y0,z0) are either in the relation if they satisfy the given formula, or else they are not. A relational database uses this concept with a few additional requirements. First, and most important, the size of the relation must be finite. The product relation given above doesn't satisfy that requirement, because there are infinitely many 3-tuples that satisfy the formula. There are a number of other considerations that have more to do with what is practical or useful on real computers solving real problems. A better way of thinking about the problem is to think about where each type of persistence mechanism specifically works better than the other. You already recognize that a relational solution makes sense when you have many separate datasets (tables) that must support relationships between them (foreign key constraints), which is almost impossible to enforce with a key-value store. Another real advantage to relational is the way it makes rich, ad-hoc queries possible with the use of proper indexes. This is a consequence of the database layer actually understanding the data that it is representing. A key-value store has it's own set of advantages. One of the more important is the way that key-value stores scale out. It is no consequence that memcached, couchdb, hadoop all use key-value storage, because it is easy to distribute key-value lookup across multiple servers. Another area that key-value storage works well is when the key or value is opaque, such as when the stored item is encrypted, only to be readable by it's owner. To drive this point home, that a Relational database works well even when you just don't need more than one table, consider the following (not original) SELECT t1.actor1 FROM workswith AS t1, workswith AS t2, workswith AS t3, workswith AS t4, workswith AS t5, workswith AS t6 WHERE t1.actor2 = t2.actor1 AND t2.actor2 = t3.actor1 AND t3.actor2 = t4.actor1 AND t4.actor2 = t5.actor1 AND t5.actor2 = t6.actor1 AND t6.actor2 = "Kevin Bacon"; Which, obviously uses a single table: workswith to compute every actor with a bacon number of 6
1,697,607
1,697,615
Naming confusion? Is having objects named FlowerGroup and FlowerGroups confusing?
I'm writing a program and I seem to be creating alot of objects where one object will be the singular form and then the collection is the plural form. eg SalesGroup SalesGroups Is this confusing for other programmers to read my code?
should not be confusing, in fact I find it pretty informative and clear; unless you have multiple kinds of collections (lame example: suppose you have an array but also a map of SalesGroup, then SalesGroups would not be the best choice but you'd rather pick SalesGroupArray, SalesGroupMap etc.)
1,697,609
1,697,947
Refactoring function calls while reducing code duplication of resulting class definitions
I have a header file with about 400 function declarations and its corresponding source file with the definitions. In order to replace the implementation with a mock at runtime, I want to replace the implementation with calls to an object that will contain the implementation instead (pointer to implementation - pImpl). This means I will have the following files: mainFile.h - contains the method declarations as before (must remain as I cannot replace the interface with the client code) IImpl.h - Abstract base (interface) for the implementation object mainFile.cpp - Will contain method definitions where all it does it call the corresponding method on IImpl* SpecificImpl.cpp - Contains the declaration and definition of the specific implementation MockImpl.cpp - Contains the declaration and definition of the implementation used during testing The main problem with this is the duplication of the 400 method declarations which appear in the main header file and again in each class definition. Is there any way I can avoid this duplication? I was trying with macros, but then the order of the includes became too specific...
What about something like this: //======================================= // Macro definition of method list //======================================= #define METHOD_LIST(ABSTRACT) \ virtual void Foo1() ABSTRACT; \ virtual void Foo2() ABSTRACT; \ virtual void Foo3() ABSTRACT //======================================= // Declaration of Abstract base class //======================================= class IBase { public: METHOD_LIST( = 0); }; //======================================= // Declaration of Specific //======================================= class CSpecific : public IBase { public: METHOD_LIST(); }; //======================================= // Declaration of Mock class //======================================= class CMock : public IBase { public: METHOD_LIST(); }; Update... If you want to make it even more macro-cryptic, you may change the macro to: #define METHOD_LIST(VIRTUAL, ABSTRACT) \ VIRTUAL void Foo1() ABSTRACT; \ VIRTUAL void Foo2() ABSTRACT; and this will allow you to declare the regular function list that is not part of any object too: For abstract class: METHOD_LIST(virtual, =0) For derived class: METHOD_LIST(virtual, ;) For regular function list: METHOD_LIST(;, ;) If you need to debug this mess, then I recommend using 'g++ -M' to see the result of the preprocessor .
1,697,683
1,697,735
Horner's rule in C++
While trying to evaulate polynomials using Horner's Rule I have a sample code segment like so: int Horner( int a[], int n, int x ) { int result = a[n]; for(int i=n-1; i >= 0 ; --i) result = result * x + a[i]; return result; } I understand that a is an array of coefficients and that x is the value that I would like to evaluate at. My question is what is the n for?
n is the degree of the polynome (and a polynome of degree n, aside from 0 which is kind of special, has n+1 coefficients, so size of array = n+1, n = size of array - 1)
1,697,852
1,697,861
C/C++/Objective-C text recognition library
Does anyone know of any free/open-source text recognition libraries in C/C++/Objective-C? Basically something that can scan an image, and read out all of the plain text.
The most famous one is Tesseract OCR developed initially by Motorola and later become open source. It is also promoted by Google. There are a few more, perhaps not as famous as Tesseract: http://en.wikipedia.org/wiki/OCRopus http://jocr.sourceforge.net/
1,697,931
1,703,466
How to use "billboards" to create a spherical object on the screen
I am tasked with making a sun/moon object flow across the screen throughout a time-span (as it would in a regular day). One of the options available to me is to use a "billboard", which is a quad that is always facing the camera. I have yet to use many direct x libraries or techniques. This is my first graphics project. How does this make sense? And how can you use this to move a sun object across a screen? Thanks :) This will be run on windows machines only and I only have the option for direct x (9). I have gotten this half working. I have a sun image displaying, but it sits at the front of my screen overtop of 80% of my screen, no matter which way my camera is pointing. I'm looking down towards the ground? Still a huge sun there. Why is this? Here is the code I used to create it... void Sun::DrawSun() { std::wstring hardcoded = L"..\\Data\\sun.png"; m_SunTexture = MyTextureManager::GetInstance()->GetTextureData(hardcoded.c_str()).m_Texture; LPD3DXSPRITE sprite = NULL; if (SUCCEEDED(D3DXCreateSprite(MyRenderer::GetInstance()->GetDevice(), &sprite))) { //created! } sprite->Begin(D3DXSPRITE_ALPHABLEND); D3DXVECTOR3 pos; pos.x = 40.0f; pos.y = 20.0f; pos.z = 20.0f; HRESULT someHr; someHr = sprite->Draw(m_SunTexture, NULL, NULL, &pos, 0xFFFFFFFF); sprite->End(); } Obviously, my position vector is hardcoded. Is this what I need to be changing? I have noticed in the documentation the possibility of D3DXSPRITE_BILLBOARD rather than D3DXSPRITE_ALPHABLEND, will this work? Is it possible to use both? As per the tutorial mentioned in an earlier post, D3DXSPRITE is a 2d object, and probably will not work for displaying within the 3d world? What is a smarter alternative?
Okay im not a direct x expert so i am going to assume a few things. First i am assuming you have some sort of DrawQuad() function that takes the 4 corners and a texture inside your rendering class. First we want to get the current viewport matrix D3DMATRIX mat; hr = m_Renderer->GetRenderDevice()->GetTransform(D3DTS_VIEW,&mat); Lets just set some sort of arbitrary size float size = 20.0f; Now we need to calculate two vectors the up unit vector and the right unit vector. D3DXVECTOR3 rightVect; D3DXVECTOR3 viewMatrixA(mat._11,mat._21,mat._31); D3DXVECTOR3 viewMatrixB(mat._12,mat._22,mat._32); D3DXVec3Normalize(&rightVect, &viewMatrixA); rightVect = rightVect * size * 0.5f; D3DXVECTOR3 upVect; D3DXVec3Normalize(&upVect, &viewMatrixB); upVect = upVect * size * 0.5f; Now we need to define a Location for our object, i am just going with the origin. D3DXVECTOR3 loc(0.0f, 0.0f, 0.0f); Lets load the sun texture: m_SunTexture = <insert magic texture load> Now lets figure out the 4 corners. D3DXVECTOR3 upperLeft = loc - rightVect; D3DXVECTOR3 upperRight = loc + upVect; D3DXVECTOR3 lowerRight = loc-upVect; D3DXVECTOR3 lowerLeft= loc + rightVect; Lets draw our quad. I am assuming this function exists otherwise you'll need to do some vertex drawing. m_Renderer->DrawQuad( upperLeft.x, upperLeft.y, upperLeft.z, upperRight.x, upperRight.y, upperRight.z, lowerRight.x, lowerRight.y, lowerRight.z, lowerLeft.x, lowerLeft.y, lowerLeft.z, m_SunTexture); Enjoy :)!
1,697,965
1,697,972
initializer-string for array of chars is too long
I keep getting this error: initializer-string for array of chars is too long Even if I change num and length to 1, it still gets the error: #include <iostream> #include <cstring> using namespace std; int main() { const int num = 11; const int length = 25; char array[num][length] = { "Becky Warre, 555-1223" "Joe Looney, 555-0097" "Geri Palmer, 555-8787" "Lynn Presnell, 555-1212" "Holly Gaddis, 555-8878" "Sam Wiggins, 555-0998" "Bob Kain, 555-8712" "Tim Haynes, 555-7676" "Warren Gaddis, 555-9037" "Jean James, 555-4939" "Ron Palmer, 555-2893" }; char search[length]; cout << "Enter a string to search: "; cin.getline(search, length); char *ptr = NULL; int i; for (i = 0; i < num; i++) { ptr = strstr(array[num], search); if (ptr != NULL) cout << array[i]; } if (ptr == NULL) cout << "No match found" << endl; return 0; }
I think it's because there aren't any commas in your array initialization... char array[num][length] = { "Becky Warre, 555-1223", "Joe Looney, 555-0097", "Geri Palmer, 555-8787", "Lynn Presnell, 555-1212", "Holly Gaddis, 555-8878", "Sam Wiggins, 555-0998", "Bob Kain, 555-8712", "Tim Haynes, 555-7676", "Warren Gaddis, 555-9037", "Jean James, 555-4939", "Ron Palmer, 555-2893" }
1,698,010
1,698,024
C++ Templated return
I have a program which is built on "Entities", which hold "Components" (composition FTW). Components may include many different types including scripts, assets, etc. I would like to build an Entity function called Entities have a map of strings, and actual Components, such that the Components can be searched for by type name. I would like to have a function called <Component T>GetComponent(char* TypeName, <T>); Which takes in a string and a type name, and which returns the typed component that is requested. Is it possible to do such a thing with C++ templates? The above clearly does not work, and I'm not sure how to go about it. Thanks Edit: I'm not looking for a factory. Entity holds instances of different types of components. Currently this is done with std::vector<Component> componentList; and an std::vector<char*> componentNames; Whose indexes are guaranteed to be the same. Likely I will write a proper map later. I simply want GetComponent to return a properly typed reference to the already instantied component of type name held by Entity in the ComponentList.
Does your function create components? Then it is a factory. You could wrap it in that template in order to save clients the (potentially erroneous) casting. The type of the function template would look like this: template< typename T > T* GetComponent(const char*); // presuming it returns a pointer and it would be called like this: Foo* foo = GetComponent<Foo>("foo");
1,698,265
1,699,628
Unexpected results using istringstream for string to double conversion in C++
I'm currently trying to take a string ("0.1") and convert it to a double using C++ in Xcode on 10.6 with gcc4.2. I'm using a function I pinched from another question, but when I try to use the function, my input according to gdb is (string)"0.1", but my output is (double)2.1220023981051542e-314. Here is my snippet copied straight out the code: double strToDouble(std::string const &numberString) { istringstream inStream(numberString); double doubleValue; inStream >> doubleValue; if(!(inStream && (inStream >> std::ws).eof())) { return 0.0; } return doubleValue; }; I'm using C++ rather than Obj-C, as it will probably have to be compiled on a *nix or windows machine eventually. I'm naturally a PHP programmer, but have some number crunching I need to speed up, so I'm doing it in a compiled language. It's been a long time since University dealing with a lower level language =P. So, if anyone has an ideas, it would be greatly appreciated... Drew J. Sonne. Full code: #include <iostream> #include <vector> #include <string> #include <sstream> using namespace std; /* * @var delimiters the string to define a break by * @var str the string to break * @var tokens where to store the broken string parts. */ void explode(const string& delimiters, const string& str, vector<string>& tokens) { // Skip delimiters at beginning. string::size_type lastPos = str.find_first_not_of(delimiters, 0); // Find first "non-delimiter". string::size_type pos = str.find_first_of(delimiters, lastPos); while (string::npos != pos || string::npos != lastPos) { // Found a token, add it to the vector. tokens.push_back(str.substr(lastPos, pos - lastPos)); // Skip delimiters. Note the "not_of" lastPos = str.find_first_not_of(delimiters, pos); // Find next "non-delimiter" pos = str.find_first_of(delimiters, lastPos); } }; /* * @var numberString double to be converted as a string. */ double strToDouble(std::string const &numberString) { istringstream inStream(numberString); double doubleValue; inStream >> doubleValue; if(!(inStream && (inStream >> std::ws).eof())) { return 0.0; } return doubleValue; }; class Cluster { private: vector<double> latStore; vector<double> lngStore; public: Cluster(int,string,string); }; /* * @var latString a comma seperated list of doubles for the latitudes. * @var lngString a comma separated list of doubles for the longitudes. */ Cluster::Cluster(int newLocationLength, string latString, string lngString) { // mark our vectors vector<string> latStoreString; vector<string> lngStoreString; // Explode our input strings. explode(",", latString, latStoreString); explode(",", lngString, lngStoreString); for( int i = 0; i < latStoreString.size(); i++) { // Grab the latitude and store it. string tempLat = latStoreString[i]; double latDouble = strToDouble(tempLat); latStore.push_back( strToDouble(tempLat) ); // Grab the longitude and store it. string tempLng = lngStoreString[i]; lngStore.push_back( strToDouble(tempLng) ); } } int main (int argc, char * const argv[]) { Cluster *rect = new Cluster("0.1,0.4","0.1,0.4"); return 0; }
This may be caused by STL Debug mode. Remove the _GLIBCXX_DEBUG macros in your target's Preprocessor Macros build setting. C++ Debug builds broke in Snow Leopard X-Code
1,698,294
1,698,326
What is best practice for C++ Public API?
What is best practice for C++ Public API? I am working on a C++ project that has multiple namespaces, each with multiple objects. Some objects have the same names, but are in different namespaces. Currently, each object has its own .cpp file and .h file. I am not sure how to word this... Would it be appropriate to create a second .h file to expose only the public API? Should their be a .h file per namespace or per object or some other scope? What might be a best practice for creating Public APIs for C++ libraries? Thanks For Any Help, Chenz
It is sometimes convenient to have a single class in every .cpp and .h pair of files and to have the namespace hierarchy as the directory hierarchy. For instance if you have this class: namespace stuff { namespace important { class SecretPassword { ... }; } } then it will be in two files: /stuff/important/SecretPassword.cpp /stuff/important/SecretPassword.h another possible layout might be: /src/stuff/important/SecretPassword.cpp /include/stuff/important/SecretPassword.h
1,698,388
1,698,413
illegal reference to non-static member 'Sun::m_SunTexture'
I am not overly competent in C++ and this compiler error is just making no sense to me. The following line calls the compiler error shown in the title: m_SunTexture = LudoTextureManager::GetInstance()->GetTextureData(hardcoded.c_str()).m_Texture; where m_SunTexture is defined in my header file as IDirect3DTexture9 *m_SunTexture; in the private section of my header file. Why is this! This makes no sense to me. Here is more code, as requested. m_SunTexture is being called in this function void Sun::DrawSun() { std::wstring hardcoded = L"..\\Data\\sun.jpg"; m_SunTexture = LudoTextureManager::GetInstance()->GetTextureData(hardcoded.c_str()).m_Texture; //more code here, cut off because it's useless for this. } DrawSun is defined in the header file as: static void DrawSun(); under the public section of my header file.
I'm guessing that the first line of code is in a static function, which is referring to the non-static member "m_SunTexture". See this for more information. Essentially, static functions don't have a "this" pointer, so referring to non-static members (which belong to each instance of the class) doesn't make any sense.
1,698,660
1,698,665
When I change a parameter inside a function, does it change for the caller, too?
I have written a function below: void trans(double x,double y,double theta,double m,double n) { m=cos(theta)*x+sin(theta)*y; n=-sin(theta)*x+cos(theta)*y; } If I call them in the same file by trans(center_x,center_y,angle,xc,yc); will the value of xc and yc change? If not, what should I do?
Since you're using C++, if you want xc and yc to change, you can use references: void trans(double x, double y, double theta, double& m, double& n) { m=cos(theta)*x+sin(theta)*y; n=-sin(theta)*x+cos(theta)*y; } int main() { // ... // no special decoration required for xc and yc when using references trans(center_x, center_y, angle, xc, yc); // ... } Whereas if you were using C, you would have to pass explicit pointers or addresses, such as: void trans(double x, double y, double theta, double* m, double* n) { *m=cos(theta)*x+sin(theta)*y; *n=-sin(theta)*x+cos(theta)*y; } int main() { /* ... */ /* have to use an ampersand to explicitly pass address */ trans(center_x, center_y, angle, &xc, &yc); /* ... */ } I would recommend checking out the C++ FAQ Lite's entry on references for some more information on how to use references properly.
1,698,796
1,698,813
Problem reading and writing from same file within same program... C++
I'm working on a program, that needs to load data from a text file upon starting and save data to THE SAME text file upon exit. I have the load working, and i have the save working, but for some reason I cant seem to have them both work within the same program. This doesnt work... ifstream loadfile("test.txt"); ofstream savefile("test.txt"); void load() { string name; while(!loadfile.eof()) { getline(loadfile,name); cout<<"name " << name<<"\n"; } } void save(User &name) { savefile << name.getName() << endl; } Neither does this... fstream file("test.txt"); void load() { string name; while(! file.eof()) { getline(file,name); cout<<"name " << name<<"\n"; } } void save(User &name) { file << name.getName() << endl; } The thing is, I can save a list of names, which works fine... but as soon as i start the program, all the names from the list delete from the text file. Also, I know that getline() gets the data from the text file as a string type, but how would i convert that to something like an int. Thanks
ofstream savefile("test.txt"); is equivalent to: ofstream savefile; savefile.open("test.txt", ios::out|ios::trunc); That is, you're truncating the file as you open it. So, move the initialization of savefile to happen after you're done with your load call (I'd suggest doing it as late as possible, because if you crash after that initialization and before you're done saving, the save file is corrupted -- normally one writes to a different file and only does the rename at the very end when everything is safe on disk).
1,698,838
1,698,908
What is wrong with this c++ typedef?
This is a piece of my code, I have more class like MathStudent, ArtStudent, etc. which inherits Student class. When I tried to compile, it says "forbids declaration of `vector' with no type," what is the problem here? thanks class Student { public: typedef vector<Student> Friends; // something wrong here? virtual unsigned int getId() = 0; //some more pure virtual functions... };
One problem with the typedef is that class Student is an abstract class, so it cannot be default constructed, which is required for types that vectors can be composed of. Another issue (say you removed the fact that class Student is abstract) might be that the class isn't fully defined. You can, in fact, declare a typedef for a vector<> with an incomplete class, but you wouldn't be able to actually use the typedef until the class was fully defined - except to declare pointers or references to the type. In both a cases you may need to think about the class's overall design - you may want to have a vector<Student*> instead so the vector can hold any type of student (using pointers since it can't hold an actual abstract Student object). As others have mentioned using smart pointers (but not std::auto_ptr<>) would help with managing the lifetimes of object pointed to by the vector.
1,699,015
1,699,051
C++ Template specialization to provide extra member function?
how do I provide extra member function for specialized template in a non-inline way? i.e. template<typename T> class sets { void insert(const int& key, const T& val); }; template<> class sets<bool> { void insert(const int& key, const bool& val); void insert(const int& key){ insert(key, true); }; }; But when I write sets<bool>::insert(const int& key) as template<> class sets<bool> { void insert(const int& key, const bool& val); void insert(const int& key); }; template<> void sets<bool>::insert(const int& key) { insert(key, true); } GCC complains: template-id ‘insert<>’ for ‘void ip_set::insert(const int&)’ does not match any template declaration
That's because it is not a function of your template so don't use "template<>". It works for me after removing "template<>" as below: void sets<bool>::insert(const int& key) { insert(key, true); } My system FC9 x86_64. The entire code: template<typename T> class sets { public: void insert(const int& key, const T& val); }; template<> class sets<bool> { public: void insert(const int& key, const bool& val) {} void insert(const int& key); }; void sets<bool>::insert(const int& key) { insert(key, true); } int main(int argc, char **argv) { sets<bool> ip_sets; int key = 10; ip_sets.insert(key); return 0; }
1,699,057
1,699,141
Why are two different concepts both called "heap"?
Why are the runtime heap used for dynamic memory allocation in C-style languages and the data structure both called "the heap"? Is there some relation?
Donald Knuth says (The Art of Computer Programming, Third Ed., Vol. 1, p. 435): Several authors began about 1975 to call the pool of available memory a "heap." He doesn't say which authors and doesn't give references to any specific papers, but does say that the use of the term "heap" in relation to priority queues is the traditional sense of the word.
1,699,307
1,699,318
How to deal with initialization of non-const reference member in const object?
Let's say you have a class class C { int * i; public: C(int * v):i(v) {}; void method() const; //this method does not change i void method(); //this method changes i } Now you may want to define const instance of this class const int * k = whatever; const C c1(k); //this will fail but this will fail because of non-const int C's constructor C(int * v) so you define a const int constructor C(const int * v):i(v) {}; //this will fail also But this will fail also since C's member "int * i" is non-const. What to do in such cases? Use mutable? Casting? Prepare const version of class? edit: After discussion with Pavel (below) I investigated this problem a bit. To me what C++ does is not correct. Pointer target should be a strict type, that means that you could not for example do the following: int i; const int * ptr; ptr = & i; In this case language grammar treats const as a promise not to change pointer's target. In addition int * const ptr is a promise not to change pointer value itself. Thus you have two places where const can be applied. Then you may want your class to model a pointer (why not). And here things are falling into pieces. C++ grammar provides const methods which are able to promise not to change field's values itself but there is no grammar to point out that your method will not change targets of your in-class pointers. A workaround is to define two classes const_C and C for example. It isn't a royal road however. With templates, their partial specializations it's hard not to stuck into a mess. Also all possible arguments variations like const const_C & arg, const C & arg, const_C & arg, C & arg don't look pretty. I really don't know what to do. Use separate classes or const_casts, each way seems to be wrong. In both cases should I mark methods which don't modify pointer's target as const? Or just follow traditional path that const method doesn't change object's state itself (const method don't care about pointer target). Then in my case all methods would be const, because class is modelling a pointer thus pointer itself is T * const. But clearly some of them modify pointer's target and others do not.
Your example doesn't fail, k is passed by value. The member i is 'implicitly constant' as direct members of C can't be changed when the instance is constant. Constness says that you can't change members after initialization, but initializing them with values in the initialization list is of course allowed - how else would you give them a value? What doesn't work is invoking the constructor without making it public though ;) update addressing updated question: Yes, C++ forces you into some verboseness sometimes, but const correctness is a common standard behaviour that you can't just redefine without breaking expectations. Pavels answer already explains one common idiom, which is used in proven libraries like the STL, for working around this situation. Sometimes you have to just accept that languages have limitations and still deal with the expectations of the users of the interface, even if that means applying an apparently sub-optimal solution.
1,699,438
1,699,461
C++ Find the number of elements in a range from an STL::multimap
I have a STL::multimap and I search it with equal_range to return an upper and lower bound. Can I find the number of elements in this range without iterating through them all and counting them one by one? #include <iostream> #include <map> using namespace std; int main () { multimap<int,int> mm; pair<multimap<int, int>::iterator,multimap<int, int>::iterator> ret; multimap<int,int>::iterator retit; for (int n=0; n<100; n++) { mm.insert ( make_pair( rand()%10,rand()%1000) ); } ret = mm.equal_range(5); int ct = 0; for (retit=ret.first; retit!=ret.second; ++retit) { cout << retit->second << endl; ct++; } cout << ct << endl; return 0; }
Use std::distance algorithm to find the distance between the iterators. Like: int ct1 = std::distance(ret.first, ret.second);
1,699,532
1,699,539
How to convert C++ class/struct to a primitive/different type/class/struct?
I have the following class CppProperty class that holds value: template<typename TT> class CppProperty { TT val; public: CppProperty(void) { } CppProperty(TT aval) : val(aval) { } CppProperty(const CppProperty & rhs) { this->val = rhs.val; } virtual ~CppProperty(void) { } TT operator=(TT aval) { this->val = aval; return this->val; } friend TT operator++(CppProperty & rhs); friend TT operator--(CppProperty & rhs); friend TT operator++(CppProperty & rhs, int); friend TT operator--(CppProperty & rhs, int); //template<typename RR> //friend RR operator=(RR & lhs, const CppProperty & rhs); //friend int & operator=(int & lhs, const CppProperty & rhs); //int reinterpret_cast<int>(const CppProperty & rhs); }; I want to do assignment like this: CppProperty<char> myproperty(10); myproperty++; int count = myproperty; How this can be done? I can't override the operator=. Any help is greatly appreciated! Thank you!
You'd need a conversion operator: operator const TT&(void) const { return val; } operator TT&(void) { return val; } There is a brief tutorial on conversion operators here. In short, when the compiler tries to convert a type, it will first look at the right-hand side for an operator that will convert it to the desired type. What we are doing is saying "Whatever TT is, this class can be converted to it". If no operators are found, it looks to see if the left-hand side can be constructed from the right-hand side, and so on. (Until, if it cannot find a conversion, it emits an error.) You can remove your explicitly defined default constructor if you declare your other constructor like this: // If not specified, construct with default-constructed type. CppProperty(TT aval = TT()) : val(aval) { }
1,699,608
1,699,624
How to get OS information whether it be LINUX or WINDOWS?
I'm running "QUdpSocket::ShareAddress" on my QT application but ShareAddress is ignored by windows. So I'm trying to solve this problem by identifying OS at run time. I heard a couple of information about window version indentifier but I couldn't see any solution to solve my problem. If there is any of advice, it would be very appreciated. Thanks.
#include <QtGlobal> ... #ifdef Q_OS_MAC // mac #endif #ifdef Q_OS_LINUX // linux #endif #ifdef Q_OS_WIN32 // win #endif See QtGlobal documentation for further information.
1,699,704
1,700,899
boost::multi_index_container with random_access and ordered_unique
I have a problem getting boost::multi_index_container work with random-access and with orderd_unique at the same time. (I'm sorry for the lengthly question, but I think I should use an example..) Here an example: Suppose I want to produce N objects in a factory and for each object I have a demand to fulfill (this demand is known at creation of the multi-index). Well, within my algorithm I get intermediate results, which I store in the following class: class intermediate_result { private: std::vector<int> parts; // which parts are produced int used_time; // how long did it take to produce ValueType max_value; // how much is it worth }; The vector parts descibes, which objects are produced (its length is N and it is lexicographically smaller then my coresp demand-vector!) - for each such vector I know the used_time as well. Additionally I get a value for this vector of produced objects. I got another constraint so that I can't produce every object - my algorithm needs to store several intermediate_result-objects in a data-structure. And here boost::multi_index_container is used, because the pair of parts and used_time describes a unique intermediate_result (and it should be unique in my data-structure) but the max_value is another index I'll have to consider, because my algorithm always needs the intermediate_result with the highest max_value. So I tried to use boost::multi_index_container with ordered_unique<> for my "parts&used_time-pair" and ordered_non_unique<> for my max_value (different intermediate_result-objects may have the same value). The problem is: the predicate, which is needed to decide which "parts&used_time-pair" is smaller, uses std::lexicographical_compare on my parts-vector and hence is very slow for many intermediate_result-objects. But there would be a solution: my demand for each object isn't that high, therefore I could store on each possible parts-vector the intermediate results uniquely by its used_time. For example: if I have a demand-vector ( 2 , 3 , 1) then I need a data-structure which stores (2+1)*(3+1)*(1+1)=24 possible parts-vectors and on each such entry the different used_times, which have to be unique! (storing the smallest time is insufficient - for example: if my additional constraint is: to meet a given time exactly for production) But how do I combine a random_access<>-index with an ordered_unique<>-index? (Example11 didn't help me on this one..)
(I had to use an own answer to write code-blocks - sorry!) The composite_key with used_time and parts (as Kirill V. Lyadvinsky suggested) is basically what I've already implemented. I want to get rid of the lexicographical compare of the parts-vector. Suppose I've stored the needed_demand somehow then I could write a simple function, which returns the correct index within a random-access data-structure like that: int get_index(intermediate_result &input_result) const { int ret_value = 0; int index_part = 1; for(int i=0;i<needed_demand.size();++i) { ret_value += input_result.get_part(i) * index_part; index_part *= (needed_demand.get_part(i) + 1); } } Obviously this can be implemented more efficiently and this is not the only possible index ordering for the needed demand. But let's suppose this function exists as a member-function of intermediate_result! Is it possible to write something like this to prevent lexicographical_compare ? indexed_by< random_access< >, ordered_unique< composite_key< intermediate_result, member<intermediate_result, int, &intermediate_result::used_time>, const_mem_fun<intermediate_result,int,&intermediate_result::get_index> > > > If this is possible and I initialized the multi-index with all possible parts-vectors (i.e. in my comment above I would've pushed 24 empty maps in my data-structure), does this find the right entry for a given intermediate_result in constant time (after computing the correct index with get_index) ? I have to ask this, because I don't quite see, how the random_access<> index is linked with the ordered_unique<> index.. But thank you for your answers so far!!
1,699,840
1,700,080
MSVC: what compiler switches affect the size of structs?
I have two DLLs compiled separately, one is compiled from Visual Studio 2008 and one is a mex file compiled from matlab. Both DLLs have a header file which they include. when I take the sizeof() the struct in one DLL it returns 48, and in the other it returns 64. I've checked the /Zp switch and in both compilations it is set to /Zp8. What other compiler switches may affect the size of a struct? The struct is a simple POCO with no inheritance and no virtual functions. Edit The struct looks like this: class LIBSPEC SGeometry { public: std::vector<IGeometry> m_i; uint N; uint n_im, n_s; }; In debug it sizeof() returns 56 in both cases, in release, in the mex compilation it's 48, from VS it's 64. I can tell matlab the exact compiler options to use when compiling the mex so it's not it. Edit After checking with offsetof, it turns out that the difference is in the size of the std::vector. in one dll it's 32 and in the other it's 48. Both dlls are x64.
Ok, so this is possibly the most obscure thing ever. It turns out that matlab add /D_SECURE_SCL=0 to the compilation which disables something called 'secure iterators' This in turn causes a difference of 16 bytes in the size of std::vector
1,700,079
1,700,227
Howto create combinations of several vectors without hardcoding loops in C++?
I have several data that looks like this: Vector1_elements = T,C,A Vector2_elements = C,G,A Vector3_elements = C,G,T ..... up to ... VectorK_elements = ... #Note also that the member of each vector is always 3. What I want to do is to create all combination of elements in Vector1 through out VectorK. Hence in the end we hope to get this output (using Vector1,2,3): TCC TCG TCT TGC TGG TGT TAC TAG TAT CCC CCG CCT CGC CGG CGT CAC CAG CAT ACC ACG ACT AGC AGG AGT AAC AAG AAT The problem I am having now is that the following code of mine does that by hardcoding the loops. Since number of Vectors can be varied, we need a flexible way to get the same result. Is there any? This code of mine can only handle up to 3 Vectors (hardcoded): #include <iostream> #include <vector> #include <fstream> #include <sstream> using namespace std; int main ( int arg_count, char *arg_vec[] ) { vector <string> Vec1; Vec1.push_back("T"); Vec1.push_back("C"); Vec1.push_back("A"); vector <string> Vec2; Vec2.push_back("C"); Vec2.push_back("G"); Vec2.push_back("A"); vector <string> Vec3; Vec3.push_back("C"); Vec3.push_back("G"); Vec3.push_back("T"); for (int i=0; i<Vec1.size(); i++) { for (int j=0; j<Vec2.size(); j++) { for (int k=0; k<Vec1.size(); k++) { cout << Vec1[i] << Vec2[i] << Vec3[k] << endl; } } } return 0; }
This will do the trick: void printAll(const vector<vector<string> > &allVecs, size_t vecIndex, string strSoFar) { if (vecIndex >= allVecs.size()) { cout << strSoFar << endl; return; } for (size_t i=0; i<allVecs[vecIndex].size(); i++) printAll(allVecs, vecIndex+1, strSoFar+allVecs[vecIndex][i]); } Call with: printAll(allVecs, 0, "");
1,700,299
1,700,365
Mutex in shared memory when one user crashes?
Suppose that a process is creating a mutex in shared memory and locking it and dumps core while the mutex is locked. Now in another process how do I detect that mutex is already locked but not owned by any process?
If you're working in Linux or something similar, consider using named semaphores instead of (what I assume are) pthreads mutexes. I don't think there is a way to determine the locking PID of a pthreads mutex, short of building your own registration table and also putting it in shared memory.
1,700,428
1,700,496
Transition from MFC to QT
Currently all our GUI components are written in MFC. Our build environment is: VC 6 Windows XP I have no idea whether: 1) We can replace all MFC components with Qt, without changing build environment ? 2) Qt will work with VC6 as any other library? You answers will help me in getting started, In the mean time I have installed Qt 4 and am trying to build some samples.
If we can replace all MFC components with QT, without changing build environment ? Yes, you even get a MFC/Qt migration framework cf qt.nokia.com/products/appdev/add-on-products/catalog/4/Windows/qtwinmigrate/ Will Qt work with VC6 as any other library ? VC6 is more than 10 years old! Qt supports VC6 until version 4.5 The next release (4.6) will drop VC6 support cf qt.nokia.com/doc/4.6-snapshot/qt4-6-intro.html#performance-optimizations
1,700,651
1,711,949
How to use speech recognition with/on video file?
How can I code speech recognition engine (Using Microsoft Speech SDK) to "listen" a video file and save the detection into a file?
This is very similar to this question and has a very similar answer. You need to separate out the audio portion, convert it to WAV format, and send it to an inproc recognizer. However, it has the same problems that I described before (requires training, assumes a single voice, and assumes the microphone is close to the speaker). If that's the case, then you can likely get reasonably good results. If that's not the case (i.e., you're trying to transcribe a TV show, or worse, some sort of camcorder audio), then the results will likely be unsatisfactory.
1,701,022
1,701,267
Boost Multi-Index : Composite key of vector and int for hashed indices
as I've just learned in in my other question, I could use a composite_key for a struct, which has a std::vector and an integer. Now my question is: Can I use this somehow to work with hashed_indecies? Here an example similar to THIS: struct unique_property { //the pair of int and std::vector<int> shall be unique int my_int; std::vector<int> my_vec; }; typedef multi_index_container< unique_property, indexed_by< hashed_unique< // indexed by my_int and every entry of my_vec composite_key< street_entry, member<unique_property,int,&unique_property::my_int>, member<unique_property,std::vector<int>,&unique_property::my_vec> > >, random_access< > > > property_locator; The problem is (of course) that a std::vector<int> is no suitable hash-key. Can I put this code in an elegant wrapper (or something like that), to produce a hash-key from every entry of my_vec as well?
Use code snippet from your suggestion here. It should work. I've added my comments there.
1,701,055
1,701,272
What is the maximum length in chars needed to represent any double value?
When I convert an unsigned 8-bit int to string then I know the result will always be at most 3 chars (for 255) and for an signed 8-bit int we need 4 chars for e.g. "-128". Now what I'm actually wondering is the same thing for floating-point values. What is the maximum number of chars required to represent any "double" or "float" value as a string? Assume a regular C/C++ double (IEEE 754) and normal decimal expansion (i.e. no %e printf-formatting). I'm not even sure if the really small number (i.e. 0.234234) will be longer than the really huge numbers (doubles representing integers)?
The standard header <float.h> in C, or <cfloat> in C++, contains several constants to do with the range and other metrics of the floating point types. One of these is DBL_MAX_10_EXP, the largest power-of-10 exponent needed to represent all double values. Since 1eN needs N+1 digits to represent, and there might be a negative sign as well, then the answer is int max_digits = DBL_MAX_10_EXP + 2; This assumes that the exponent is larger than the number of digits needed to represent the largest possible mantissa value; otherwise, there will also be a decimal point followed by more digits. CORRECTION The longest number is actually the smallest representable negative number: it needs enough digits to cover both the exponent and the mantissa. This value is -pow(2, DBL_MIN_EXP - DBL_MANT_DIG), where DBL_MIN_EXP is negative. It's fairly easy to see (and prove by induction) that -pow(2,-N) needs 3+N characters for a non-scientific decimal representation ("-0.", followed by N digits). So the answer is int max_digits = 3 + DBL_MANT_DIG - DBL_MIN_EXP For a 64-bit IEEE double, we have DBL_MANT_DIG = 53 DBL_MIN_EXP = -1023 max_digits = 3 + 53 - (-1023) = 1079
1,701,067
1,701,083
How to check that an element is in a std::set?
How do you check that an element is in a set? Is there a simpler equivalent of the following code: myset.find(x) != myset.end()
The typical way to check for existence in many STL containers such as std::map, std::set, ... is: const bool is_in = container.find(element) != container.end();
1,701,149
1,701,167
Simple C++ logger by using singleton pattern
Due to the flooding examples of implementing logger using Singleton pattern, I have just written a simple C++ logger in the same approach for my program. However, since the famous double-checked locking approach is known to be no more thread-safe, I wonder if I should: 1) Forget about the use of Singleton pattern in this case? 2) Continue to use double-checked locking even though it is unsafe? 3) Use the expensive pure sync lock method for every access to its public interfaces? Any suggestions?
Use Meyers Singleton. If you are using using gcc at least initialization is thread-safe. class Singleton{ Singleton(){ //This is threadsafe in gcc, no mutex required } static Singleton * instance(){ static Singleton myinstance; return &myinstance; } }; gcc guards static locals construction unless you disable with -fno-threadsafe-statics, I recently wrote about that here
1,701,416
1,701,456
Initialization of reference member requires a temporary variable
struct Div { int i; int j; }; class A { public: A(); Div& divs; }; In my constructor definition, I have the following implementation A::A(): divs(NULL) {} I get the following error: Error72 error C2354: 'A::divs' : initialization of reference member requires a temporary variable
A reference must be initialised to refer to something; it can't refer to nothing, so you can't default-construct a class that contains one (unless, as others suggest, you define a global "null" value). You will need a constructor that is given the Div to refer to: explicit A(Div &d) : divs(d) {} If you want it to be able to be "null", then you need a pointer, not a reference.
1,701,869
1,701,919
Unit testing. File structure
I have a C++ legacy codebase with 10-15 applications, all sharing several components. While setting up unittests for both shared components and for applications themselves, I was wondering if there are accepted/common file structures for this. Because my unit tests have several base classes in order to simplify project/customer specific test setups, there are alot of files that are common for all tests. To me it seems natural here to create a new directory that contains all the test related files, mocks etc -to have it all centralized, and also keep testing related definitions out of the main make files. On the other hand I see that it is common practice to have the test files reside together with the code files that they test. Is there a more/less accepted way of doing this?
Out of sight, out of mind; if you keep the test files together with the code files it may be more obvious to the developers that when they update a code file they should update the tests as well.
1,702,600
1,702,636
Is it possible to progressively alpha-blend between two textures in one location created with D3DXCreateTextureFromFileInMemoryEx?
I have two textures that are both .jpg, which represent a sky (one during the day, one at night). My question is, is it possible for me to fade one texture into the other? They are created with D3DXCreateTextureFromFileInMemoryEx. How can I perform this kind of transition? I don't wish to create two objects, just change the texture gradually. To be clear, I wish to, over time, slowly blend from one texture to another (and back). However, I don't wish the fade to be going on at all times. Thanks in advance for any advice you can offer.
You have quite a few options here - You can use both textures with texture blending to transition from one texture to the other. However, if you're doing this over a long period of time, you may want to precompute a third texture (the blended state) and just use it as a single texture. Occasionally, recompute the "new" state. This will potentially simplify your rendering, since you'd be using a single texture (that you change slowly over time) instead of having to always do multi-texturing just for this effect. (If you're not doing anything else but this with the objects you're texturing, and if the textures aren't huge, a simple 2 texture multi-texture is no big deal, though.)
1,702,673
1,702,709
retrieving type returned by function using "typeof" operator in gcc
We can get the type returned by function in gcc using the typeof operator as follows: typeof(container.begin()) i; Is it possible to do something similar for functions taking some arguments, but not giving them? E.g. when we have function: MyType foo(int, char, bool, int); I want to retrieve this "MyType" (probably using typeof operator) assuming I know only the name of function ("foo") and have no knowledge about arguments it takes. Is it possible?
In C++ the return value's type is not part of the method signature. Even if there is a way to get the return type of a method, you would have to deal with the possibility of getting multiple methods back and not knowing which one went with the return type you want.
1,702,929
1,703,154
String initialization with pair of iterators
I'm trying to initialize string with iterators and something like this works: ifstream fin("tmp.txt"); istream_iterator<char> in_i(fin), eos; //here eos is 1 over the end string s(in_i, eos); but this doesn't: ifstream fin("tmp.txt"); istream_iterator<char> in_i(fin), eos(fin); /* here eos is at this same position as in_i*/ //moving eos forward for (int i = 0; i < 20; ++i) { ++eos; } // trying to initialize string with // pair of iterators gives me "" // result string s(in_i, eos); Thank you.
I don't think you can advance the end iterator to a suitable position: to advance the iterator means to read input, also both iterators are referencing the same stream - therefore advancing one iterator means to advance the second. They both end up referencing the same position in the stream. Unless you are willing to write or find an iterator adaptor (boost?) that does an operation on n items referenced by some iterator, it might not be possible to initialize the string like that. Or you read the value with other methods and set the value of the string later.
1,703,006
1,703,285
3d Alternative for D3DXSPRITE for billboarding
I am looking to billboard a sun image in my 3d world (directx 9). Creating a D3DXSPRITE is great in some cases, but it is only a 2d object and can not exist in my "world" as a 3d object. What is an alternative method for billboarding, similar to d3dxsprite? How can I implement it? The only alternative I have currently found is this link: http://www.two-kings.de/tutorials/dxgraphics/dxgraphics17.html which does not seem to work
Taking the center of your object vCenter. The object has a width and height of (w,h). Firstly you need your camera to billboard vector. This is calculated as vCamToCen = normalise( vCamera - vCenter ). You then need an appropriate rough up vector. This can be extracted from the view matrix (handily described here, ie the second column). You can then calculate the side vector by doing vSide = vCamToCen x vUp. Then calculate the REAL up vector by doing vUp = vCamToCen x vSide. Where 'x' is a cross product. You now have all the info you need to do your billboarding. You can then form your 4 verts as follows. const float halfW = w / 2.0f; const float halfH = h / 2.0f; const D3DXVECTOR3 vHalfSide = vSide * halfW; const D3DXVECTOR3 vHalfUp = vUp * halfH; vertex[0].pos = vCenter; vertex[1].pos = vCenter; vertex[2].pos = vCenter; vertex[3].pos = vCenter; vertex[0].pos -= vHalfSide; vertex[0].pos -= vHalfUp; vertex[1].pos += vHalfSide; vertex[1].pos -= vHalfUp; vertex[2].pos += vHalfSide; vertex[2].pos += vHalfUp; vertex[3].pos -= vHalfSide; vertex[3].pos += vHalfUp; Build your 2 triangles out of those verts and pass it through your pipeline as normal (ie with your normal view and projection matrices).
1,703,011
1,718,162
Data Destruction In C++
So, for class I'm (constantly re-inventing the wheel) writing a bunch of standard data structures, like Linked Lists and Maps. I've got everything working fine, sort of. Insertion and removal of data works like a charm. But then main ends, my list is deleted, it calls it's dtor and attempts to delete all data inside of it. For some reason, this results in a double free event. All data is inserted into the list by these methods: /* Adds the specified data to the back of the list. */ template<typename T, class COMPFUNCTOR> void List<T, COMPFUNCTOR>::append(T* d) { if(tail != NULL) {//If not an empty list, simply alter the tail. tail->setNext(new ListNode<T>(d)); tail = tail->getNext(); } else {//If an empty list, alter both tail and head. head = tail = new ListNode<T>(d); } size++; }; /* Adds a copy of the specified data to the back of the list. */ template<typename T, class COMPFUNCTOR> void List<T, COMPFUNCTOR>::append(const T& d) { this->append(new T(d)); }; The first method assumes that it owns the data passed into it; the second copies data passed into it. Now, for main: int main(int argc, char** argv) { parser = new Arguments(argc, argv); //Uses a map<char, list<string>>; no direct bugs, insertion works fine. if(parser->flagSet('f')) { printf("%s\n", parser->getArg('f').getFirst().str.c_str()); } return 0; } This results in a stack dump, for a double free event. The list destructor is defined as follows: /* Destroys the List and all data inside it. */ template<typename T, class COMPFUNCTOR> List<T, COMPFUNCTOR>::~List() { while(head != NULL) { ListNode<T>* tmp = head; //Set up for iteration. head = head->getNext(); if(tmp->getData() != NULL) //Delete this node's data then the node itself. delete tmp->getData(); delete tmp; } }; If I comment out either the list destructor or the code in main's if statement, the program runs fine. Now, I'm not sure where this double delete is coming from. List is destroyed on the end of main, which results in it deleting the data inside of it; which is either owned or copied into it, and only copies ever come out of it (the only time list passes out pointers of it's data is when you remove it from the list). Obviously, something is created on the stack in main, when parser->getArg('f').getFirst(); is called. I read this as, (de-ref pointer to parser)->(get a reference of the linked list).(acquire a copy of the first element in list [an std::string]); Deleting a pointer to parser is no big deal (In fact, I should probably delete that, oops); deleting a reference shouldn't be a big deal either (just a candied up pointer); and deleting a copy of the first element should be a non-issue. Where have I gone wrong? EDIT The code for ListNode is as follows: /* Create a ListNode with the specified neighbor. */ template<typename T> ListNode<T>::ListNode(T* d, ListNode<T>::ListNode* neighbor) { data = d; next = neighbor; } /* Deletes the ListNode. */ template<typename T> ListNode<T>::~ListNode() { next = NULL; if(data != NULL) delete data; data = NULL; } ListNodes only ever take pointers to their data, they only ever delete their data when they die with non-null data pointers. The List itself also only ever deletes stuff if it is non-null. All deleted data is set to NULL. Oh, and the data right now is std::string, I have no control over it's copy constructor, but I would assume it's properly implemented.
Looking at your ListNode class it is obvious that there is an ownership mismatch. It is a good rule of thumb for design that not only should every allocation be matched by a matching de-allocation but that these should be performed by at the same layer in the code or ideally by the same object. The same applies to any resource whose acquisition needs to be paired with a release. It's obvious that this guideline isn't being followed here and that is a root of a lot of your issues. template<typename T> ListNode<T>::ListNode(T* d, ListNode<T>::ListNode* neighbor) { data = d; next = neighbor; } template<typename T> ListNode<T>::~ListNode() { next = NULL; if(data != NULL) delete data; data = NULL; } ListNode deletes something that it didn't allocate. While you allow for the possibility of a null data member, you are going to make things simpler if you don't allow this. If you want a list of optional items you can always use you're template with a smart pointer type or a boost::optional. If you do this, and then make sure that your ListNode class always allocates and deallocates the copy of the item, you can then make the data member a T instead of a T*. This means that you can make your class something like this: template<typename T> class ListNode { public: explicit ListNode( const T& d ) : data(d), next() { } T& getData() { return data; } const T& getData() const { return data; } ListNode* getNext() const { return next; } void setNext(ListNode* p) { next = p; } private: ListNode* next; T data; } I've moved to using references for things which can't now be null. Also, everything that's owned is now a data member and things that that class doesn own (next) are referred to by pointer. Of these two functions, I hope that the second was a private function because your destructor always assumes that the List (via a ListNode) owns the data pointer so having a public function which takes a raw pointer that doesn't take a copy is potentially dangerous. template<typename T, class COMPFUNCTOR> void List<T, COMPFUNCTOR>::append(T* d); template<typename T, class COMPFUNCTOR> void List<T, COMPFUNCTOR>::append(const T& d); With the change to ListNode above we can implement the second of these without needing the help of the first quite simply. template<typename T, class COMPFUNCTOR? void List<T, COMPFUNCTOR>::append(const T& d) { ListNode<T>* newNode = new ListNode<T>(d); if (!tail) tail->setNext( newNode ); else head = newNode; tail = newNode; size++; } The destructor 'walk' for the List remains similar to what you have except there should be no attempt to manually delete the owned data of the ListNode, that happens automatically when you delete the ListNode itself. Note: all my code is untested, it's for exposition only!
1,703,017
1,703,057
Passing another class amongst instances
I was wondering what is the best practice re. passing (another class) amongst two instances of the same class (lets call this 'Primary'). So, essentially in the constructor for the first, i can initialize the outside instance (lets call this 'Shared') - and then set it to a particular value whilst im processing this class in main(). So 'Shared', may be an int, say 999 by now. Now what if i create another instance of the main class 'Primary'? whats the best way to access the already initialized outside instance of 'Shared' - because if i don't handle this correctly, the constructor for 'Primary', when called again will just go ahead and create one more instance of 'Shared', and thus i loose the value 999.. i can think of some messy solutions involving dynamic pointers and if statements (just) but i have a feeling there might be a simpler, cleaner solution?
As I understand it: You have a class A You have a class B For all members of class A there is a single instance of class B You did not mention if any parameters from the A constructor are used to initialize B! What happens to the parameters of the second A that are used for B? So we will assume that B is default constructed. We will also assume that you need the instance of B to be lazily evaluated otherwise you would just use a static member. class A { B& bRef; public: A() :bRef(getLazyB()) // Get a reference to the only B for your object. {} private: static B& getLazyB() { static B instance; // Created on first use return instance; // returned to all users. } };
1,703,322
1,703,521
Serialize Strings, ints and floats to character arrays for networking WITHOUT LIBRARIES
I want to transmit data over the network, but I don't want to use any foreign libraries (Standard C/C++ is ok). for example: unsigned int x = 123; char y[3] = {'h', 'i', '\0'}; float z = 1.23f; I want this in an char xyz[11]; array. Note: To transmit it over network, I need Network Byte order for the unsigned int (htonl function), then I need to somehow serialize the float to be in IEEE 754 form (theres many functions on the internet), and I know it. How do I get them into the the xyz-Array, nicely lined up end to end, so I can use this as a buffer for my socket + send() function? Obviously I have reverse functions (ntohl, and a reverse IEEE 754) to get them out but I need a technique there too, preferably the same... It would be something like this: xyz in binary: 00000000 0000000 00000000 01111011 | 01101000 | 01101001 | 00000000 | 00111111 10011101 01110000 10100100 - big endian repr. of u. int 123 - | - 'h' - | - 'i' - | - '\0' - | - IEEE 754 repr of float 1.23 - How can I accomplish this without external libraries and minimal use of standard library functions? This isn't so much for my program as for me to learn from.
Ah, you want to serialize primitive data types! In principle, there are two approaches: The first one is, that you just grab the internal, in-memory binary representation of the data you want to serialize, reinterpret it as a character, and use that as you representation: So if you have a: double d; you take the address of that, reinterpret that pointer as a pointer to character, and then use these characters: double *pd=&d; char *pc = reinterpret_cast<char*>(pd); for(size_t i=0; i<sizeof(double); i++) { char ch = *pc; DoSomethingWith(ch); pc++; } This works with all primitive data types. The main problem here is, that the binray representation is implementation dependent (mainly CPU dependent). (And you will run into subtle bugs when you try doing this with IEEE NANs...). All in all, this approach is not portable at all, as you have no control at all over the representation of your data. The second approach is, to use a higher-level representation, that you yourself have under control. If performance is not an issue, you could use std::strstream and the >> and << operators to stream primitive C type variables into std::strings. This is slow but easy to read and debug, and very portable on top of it.
1,703,452
1,703,940
C++, Boost regex, replace value function of matched value?
Specifically, I have an array of strings called val, and want to replace all instances of "%{n}%" in the input with val[n]. More generally, I want the replace value to be a function of the match value. This is in C++, so I went with Boost, but if another common regex library matches my needs better let me know. I found some .NET (C#, VB.NET) solutions, but I don't know if I can use the same approach here (or, if I can, how to do so). I know there is this ugly solution: have an expression of the form "(%{0}%)|(%{1}%)..." and then have a replace pattern like "(1?" + val[0] + ")(2?" + val[1] ... + ")". But I'd like to know if what I'm trying to do can be done more elegantly. Thanks!
I don't beleive boost::regex has an easy way to do this. The most straightfoward way that I can think of would be to do a regex_search using the "(%{[0-9]+}%)" pattern and then iterate over the sub-matches in the returned match_results object. You'll need to build a new string by concatenating the text from between each match (the match_results::position method will be your friend here) with the result of converting sub-matches to the values from your val array.
1,703,649
1,703,778
Adding functionality to a handle wrapper
I have a C++ RAII class for managing Win32 HANDLEs using boost::shared_ptr<> that looks a bit like this: namespace detail { struct NoDelete { void operator()( void* ) {}; }; }; // namespace detail template< typename HANDLE_TYPE, typename HANDLE_DELETER > class CHandleT { public : explicit CHandleT( HANDLE_TYPE handle, bool delete_on_release = true ) { if( delete_on_release ) handle_ = Handle( handle, HANDLE_DELETER() ); else handle_ = Handle( handle, detail::NoDelete() ); }; operator HANDLE_TYPE() const { return static_cast< HANDLE_TYPE >( handle_.get() ); }; protected: typedef boost::shared_ptr< void > Handle; Handle handle_; }; // class CHandleT struct DeallocateHandle { void operator()( void* handle ) { ::CloseHandle( handle ); }; }; typedef CHandleT< HANDLE, DeallocateHandle > CHandle; I would like to extend it such that instead writing: CHandle my_handle( ::CreateEvent( NULL, FALSE, FALSE, NULL ) ); ::SetEvent( my_handle.get() ); I could write: CEvent my_event( NULL, FALSE, FALSE, NULL ); my_event.SetEvent(); Would the best way to do that be to use the CHandle class as a member of a CEvent class? class CEvent { public: explicit CEvent( LPSECURITY_ATTRIBUTES lpEventAttributes = NULL, BOOL bManualReset = TRUE, BOOL bInitialState = FALSE, LPCTSTR lpName = NULL, bool delete_on_release = true ) : handle_( new CHandle( ::CreateEvent( lpEventAttributes, bManualReset, bInitialState, lpName ), delete_on_release ) ) { }; BOOL SetEvent() { _ASSERT( NULL != handle_ && NULL != handle_.get() ); return ::SetEvent( handle_.get() ); }; private: boost::shared_ptr< CHandle > handle_; }; // class CEvent Or, is there a better way? (Note that I still want to maintain the copy semantics of the CHandle given by boost::shared_ptr<>. Thanks, PaulH
I won't get into discussion on boost::shared_ptr or any smart ptr. And here is a few reasons why, from different angles between the lines, and why smart pointers can always and always be made redundant or beaten out. Code does seem to emulate the CLR and NT model in which case there are predefined semantics by the OS for what you're doing. It's called ::DuplicateHandle and it works well and is more suited for cross process scenarios (and would hack less than boost::interprocess or similar). And it is applicable to few other contexts. Now the second, hopefully not a contraversial bit where the poor-old-OO inheritance is neglected because containment focus wins out regurarly (yet it has nothing to do with OO really when you play mix-ins for those that continously scream: contain me ). So no matter how rare it might be, or whether it is an OO, non-OO or O(o) argument : "inheritance" wins here. Why? Because it is a waitable handle concept, including the Win32 Event, Mutex, Auto reset kinds, Thread, all of it apart from critical_section (which also has a backing handle deep within - but is specially treated in both CLR and NT, plus it has dual-nature ). Thus it makes absolute sense for: typedef CHandleT< HANDLE > WaitHandle; to be the root of the "hierarchy", along with copy semantics of what the underlying implementation already is. Lastly, it ends up the most efficient representation of your data types that are handles, as they will mimic the OS you are targetting and need no ref count or avalanche/rippling ref count either. Then came cross-platform development and boost::thread-ing and ruined the bed-time story :-)
1,703,844
1,703,966
Making an object orbit a fixed point in directx?
I am trying to make a very simple object rotate around a fixed point in 3dspace. Basically my object is created from a single D3DXVECTOR3, which indicates the current position of the object, relative to a single constant point. Lets just say 0,0,0. I already calculate my angle based on the current in game time of the day. But how can i apply that angle to the position, so it will rotate? :(? Sorry im pretty new to Directx.
So are you trying to plot the sun or the moon? If so then one assumes your celestial object is something like a sphere that has (0,0,0) as its center point. Probably the easiest way to rotate it into position is to do something like the following D3DXMATRIX matRot; D3DXMATRIX matTrans; D3DXMatrixRotationX( &matRot, angle ); D3DXMatrixTranslation( &matTrans, 0.0f, 0.0f, orbitRadius ); D3DXMATRIX matFinal = matTrans * matRot; Then Set that matrix as your world matrix. What it does is it creates a rotation matrix to rotate the object by "angle" around the XAxis (ie in the Y-Z plane); It then creates a matrix that pushes it out to the appropriate place at the 0 angle (orbitRadius may be better off as the 3rd parameter in the translation call, depending on where your zero point is). The final line multiplies these 2 matrices together. Matrix multiplications are non commutative (ie M1 * M2 != M2 * M1). What the above does is move the object orbitRadius units along the Z-axis and then it rotates that around the point (0, 0, 0). You can think of rotating an object that is held in your hand. If orbitRadius is the distance from your elbow to your hand then any rotation around your elbow (at 0,0,0) is going to form an arc through the air. I hope that helps, but I would really recommend doing some serious reading up on Linear Algebra. The more you know the easier questions like this will be to solve yourself :)
1,703,941
1,704,025
Initializing array of objects with data from text file
I’m getting system error when I try to compile the code below on Visual C++ 2008 Express. What I’m trying to do is to initialize array of objects with data read from file. I think there is something wrong inside the while loop, because when I initialize these objects manually without the while loop it seems to work. Here is the code and text file: #include <iostream> #include <string> #include "Book.h" using namespace std; int main() { const int arraySize = 3; int indexOfArray = 0; Book bookList[arraySize]; double tempPrice;//temporary stores price string tempStr;//temporary stores author, title fstream fileIn( "books.txt" ); while ( !fileIn.eof( )) { getline(fileIn,tempStr); bookList[indexOfArray].setAuthor(tempStr); getline(fileIn,tempStr); bookList[indexOfArray].setTitle(tempStr); fileIn >> tempPrice; bookList[indexOfArray].setPrice(tempPrice); if ( indexOfArray < arraySize ) //shifting array index while not exceeding array size indexOfArray++; } fileIn.close(); return 0; } and the text file: Author1 Book1 23.99 Author2 Book2 10.99 Autho3 Book3 14.56
It looks like you are trying to write to bookList[3] in the loop. You will loop through three times filling your array incrementing indexOfArray each time. This will leave indexOfArray at 3 -- your condition as it is written will allow indexOfAray to be incremented to 3. Then if you have a newline after the "14.56" in your data file you will loop one more time and attempt to pass an empty string to bookList[indexOfArray].setAuthor() leading to a segfault since indexOfArray is past the end of the array. I would suggest ditching the hard-coded array and using a std::vector instead. At the start of each loop just use push_back() to add a new book to the end of the vector and then use back() to access the new element in the array.
1,703,979
1,704,309
Which C++ logical operators do you use: and, or, not and the ilk or C style operators? why?
leisure/curiosity question as implied in the title. I personally prefer the new operators as to make code more readable in my opinion. Which ones do use yourself? What is your reason for choosing one over the other one? also Emacs highlights those operators differently so I get more visual feedback when looking at the screen. I know the old operators can be highlighted as well but the ISO646 highlighted by default
I won't use the alternative operators as they cause more confusion then clearity in my opinion. If i see an alphabetical name i expect a namespace, class, variable, function or a function style operator - the common operators divide this intuitively into sequences for me. The alternative style just doesn't fit into the C/C++ world for me. Also, while Greg has a point regarding people new to C or C++, you get used to it pretty soon - i have no problems spotting ! anywhere.
1,704,164
1,704,217
OpenGL / C++ / Qt - Advice needed
I am writing a program in OpenGL and I need some sort of interfacing toolbar. My initial reactions were to use a GUI, then further investigation into C++ I realized that GUI's are dependent on the OS you are using (I am on Windows). Therefore, I decided to use QT to help me. My Question is if I am taking the best/appropriate approach to this solution. Am I even able to write my OpenGL program and have the GUI I want to create interface with the C++ code to do what I want it to do. For example, If I create a simple "control panel" with arrows in each direction. And on screen I have a box object created by glut can I interface the arrows to be clicked on and interact with the openGL program to move the box?
Using Qt is coherent for your problem: it provides good integration of OpenGl through the QtOpenGL module. Derive your display classes from QGLWidget (until Qt 4.8) or from QOpenGLWidget (since Qt 5.4) and implement virtual methods paintGL() etc. You will have access to the Qt's signal and slot system so that you will be able to catch Gui events and update the OpenGl display.
1,704,165
1,704,358
Is there a way to improve the speed or efficiency of this lookup? (C/C++)
I have a function I've written to convert from a 64-bit integer to a base 62 string. Originally, I achieved this like so: char* charset = " 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; int charsetLength = strlen(charset); std::string integerToKey(unsigned long long input) { unsigned long long num = input; string key = ""; while(num) { key += charset[num % charsetLength]; num /= charsetLength; } return key; } However, this was too slow. I improved the speed by providing an option to generate a lookup table. The table is about 624 strings in size, and is generated like so: // Create the integer to key conversion lookup table int lookupChars; if(lookupDisabled) lookupChars = 1; else largeLookup ? lookupChars = 4 : lookupChars = 2; lookupSize = pow(charsetLength, lookupChars); integerToKeyLookup = new char*[lookupSize]; for(unsigned long i = 0; i < lookupSize; i++) { unsigned long num = i; int j = 0; integerToKeyLookup[i] = new char[lookupChars]; while(num) { integerToKeyLookup[i][j] = charset[num % charsetLength]; num /= charsetLength; j++; } // Null terminate the string integerToKeyLookup[i][j] = '\0'; } The actual conversion then looks like this: std::string integerToKey(unsigned long long input) { unsigned long long num = input; string key = ""; while(num) { key += integerToKeyLookup[num % lookupSize]; num /= lookupSize; } return key; } This improved speed by a large margin, but I still believe it can be improved. Memory usage on a 32-bit system is around 300 MB, and more than 400 MB on a 64-bit system. It seems like I should be able to reduce memory and/or improve speed, but I'm not sure how. If anyone could help me figure out how this table could be further optimized, I'd greatly appreciate it.
I agree with Rob Walker - you're concentrating on improving performance in the wrong area. The string is the slowest part. I timed the code (your original is broken, btw) and your original (when fixed) was 44982140 cycles for 100000 lookups and the following code is about 13113670. const char* charset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; #define CHARSET_LENGTH 62 // maximum size = 11 chars void integerToKey(char result[13], unsigned long long input) { char* p = result; while(input > 0) { *p++ = charset[input % CHARSET_LENGTH]; input /= CHARSET_LENGTH; } // null termination *p = '\0'; // need to reverse the output char* o = result; while(o + 1 < p) swap(*++o, *--p); }
1,704,353
1,704,441
Template lookup in class?
It's hard to get a word for this. Sometimes I see a class like this: template <typename T> class Wrapper { public: Wrapper(const T& t) : t_(t) {} Wrapper(const Wrapper& w) : t_(w.t_) {} private: T t_; } As far as I can tell this is legitimate code. However, why is the copy constructor allowed to accept a const Wrapper& without explicitly stating that it needs a const Wrapper<T>&. When else is the template type implied? Is it allowed to write the copy constructor this way if you don't use an in-class definition?
It is explicitly specified by the language standard in 14.6.1/1: Within the scope of class template, when the name of the template is neither qualified nor followed by <, it is equivalent to the name of the template followed by the template-parameters enclosed in <>. This was re-worded (through the concept of "injected class name") in the later versions of the standard, but the point is that this behavior is explicitly spelled out in the document. To answer the second part of your question, this rule also applies to parameter declarations when writing out-of-class method definitions, but it doesn't apply to the return type declarations. For example, this code is OK template <typename T> struct S { S foo(S); }; template <typename T> S<T> S<T>::foo(S s) { /* whatever */ } but you can't remove the <T> bit from the return type in the definition of the method. (And you can't remove <T> from the qualified name of the method.) As for the constructior specifically: your should use the full name (with <T>) for the class, but you should not use <T> in the name of the constructor itself. So the shortest form for out-of-class definition in your case would be template <typename T> Wrapper<T>::Wrapper(const Wrapper& w) : t_(w.t_) { } Note, that you can't add the <T> bit to the constructor name even if you want to template <typename T> Wrapper<T>::Wrapper<T>(const Wrapper& w) ^ ERROR !!! P.S. This last claim needs further research. Comeau Online compiler thinks it is an error, while GCC thinks it is OK. I'll return to it later. P.P.S. The compiler in MSVC++ 2005 complains about the latter declaration with a warning warning C4812: obsolete declaration style: please use 'Wrapper<T>::Wrapper' instead Interesting...
1,704,880
1,707,081
Custom system tray icon "balloon tooltips" for Qt?
I know that in the .NET framework there are a handful of alternative third-party controls for normal system tray icon "balloon tips", that allow you to change the colors and add some styling to the balloon. I was wondering if there is something similar for Qt, which allows for better customization of the look, style, and feel of the balloon tooltips from a system tray icon.
You should have a quick glance at the "Qt Style Sheets" examples in QtAssistant. It provides strong and many ways to alter widgets looks and feel... Maybe you'll find something interesting there ! Otherwise, you could have a look at QSystemTrayIcon & QBalloonTip. Maybe by reimplementing those classes... Hope this help a bit !
1,704,892
1,704,903
Are class variables included in the 7 +- 2 guideline?
I'm wondering in regards to the guideline stating that classes should have around 7 variables +-2, are class variables (class constants) included in this? Ex: class Foo { static const int SOME_THING; static const double SOME_OTHER; static const int BLAH; int m_ThisVariable; double m_ThatVariable; string m_SomeString; public: //.... }; Would you consider the above to count as 3 or 6 in regards to the 7 +- 2 rule?
Anyone who honestly thinks that you can arbitrarily define how many member variables a class should have has not written a lot of code or are extremely arrogant. I know it just a guideline, but honestly, if the class is well defined, conforms to the general OOP guidelines of single responsibility, and is easy to maintain, you should just spend your time solving real problems. BTW, I realize that this is not an actual answer, so let the downvoting begin. I just had to vent :) EDIT: Just did a little searching and found that this 'guideline' comes from the fact that humans have trouble remembering sequences of information with more than five or six discrete data points. Well, that's nice, and it is something to remember (especially when designing user interfaces), but in practice you cannot design your code this way. Do what makes sense and makes your life easier (maintenance considerations being part of that decision).
1,704,895
1,705,053
Access violation when calling external function (C++) from Delphi application
I've an external DLL written in C++. The piece below declares a struct type and a function, which, being given a pointer, fills a variable of this type: enum LimitType { NoLimit, PotLimit, FixedLimit }; struct SScraperState { char title[512]; unsigned int card_common[5]; unsigned int card_player[10][2]; unsigned int card_player_for_display[2]; bool dealer[10]; bool sitting_out[10]; CString seated[10]; CString active[10]; CString name[10]; double balance[10]; bool name_good_scrape[10]; bool balance_good_scrape[10]; double bet[10]; double pot[10]; CString button_state[10]; CString i86X_button_state[10]; CString i86_button_state; CString button_label[10]; double sblind; double bblind; double bbet; double ante; LimitType limit; double handnumber; bool istournament; }; extern "C" { SCRAPER_API int ScraperScrape(HWND hwnd, SScraperState *state); } I declare a similar type in my Delphi application and call the above function: interface type LimitType = (NoLimit, PotLimit, FixedLimit); SScraperState = record title: Array [0..511] of Char; card_common: Array [0..4] of Word; card_player: Array [0..9, 0..1] of Word; card_player_for_display: Array [0..1] of Word; dealer: Array [0..9] of Boolean; sitting_out: Array [0..9] of Boolean; seated: Array [0..9] of String; active: Array [0..9] of String; name: Array [0..9] of String; balance: Array [0..9] of Double; name_good_scrape: Array [0..9] of Boolean; balance_good_scrape: Array [0..9] of Boolean; bet: Array [0..9] of Double; pot: Array [0..9] of Double; button_state: Array [0..9] of String; i86X_button_state: Array [0..9] of String; i86_button_state: String; button_label: Array [0..9] of String; sblind: Double; bblind: Double; bbet: Double; ante: Double; limit: LimitType; handnumber: Double; istournament: Boolean; end; pSScraperState = ^SScraperState; function ScraperScrape(hWnd: HWND; State: pSScraperState): Integer; cdecl; external 'Scraper.dll'; implementation var CurState: SScraperState; pCurState: pSScraperState; if ScraperScrape(hWnd, pCurState) = 0 then ... When the function is called I get Debugger Exception Notification: Project ... raised exception class EAccessViolation with message 'Access violation at address 10103F68 in module 'Scraper.dll'. Read of address FFFFFFFC'. Process stopped. Other functions exported from the same DLL work fine, so my guess is I made a mistake in the type declaration. Any tips will be highly appreciated, as I'm dead stuck at this point.
The main problem id that C++ CString and Delphi String are incompatible types. If you want to pass data in this manner, you should use either fixed length character arrays or C-Style null terminated strings (PChar in Delphi). C++ would be something like: char Dealer[100][10]; Please edit if wrong - it been many years since I done any C coding Delphi Dealer : packed array[0..9, 0..99] of char; or type TDealer = packed array[0..99] of char; ... Dealer : arry[0..9] of TDealer; or if using C-string (TCHAR in API code) Dealer: array[0..9] of PAnsiChar; // or PWideChar if source is UCS-16 Also note that String, Char (and hence PChar) changed from single byte to double byte (UCS 16) in Delphi 2009. Other data types may be different as well e.g. In Delphi Word is 16bit, but may be different in C++. If possible use specific types that are common in the Windows API, such as USHORT instead of "unsigned int" and Word
1,705,147
1,705,166
Struct initialization of the C/C++ programming language?
I could do struct initialization with code: struct struct_type_id struct_name_id = { value1, value2, value3 }; but could not with: struct struct_type_id struct_name_id; struct_name_id = { value1, value2, value3 }; why I could do it with the former,but could not with the latter with gcc,g++,vc2008,vc6?In other words,why the c/c++ programming language do not support this syntax? thanks.
The first statement creates a variable initialized to the given values, i.e., these values are built in memory and stored directly in the program executable in that variable address (for globals) or ready for memory copy (for stack variables). The second statement of the second block is very different. Although it looks similar, it is an assign expression. It means that the RHS of the equals operator is an expression that is evaluated (independently of what is in the LHS of =), and then passed to the = operator. Without proper context, {...} doesn't have any meaning. In C99, you can do this: struct_name_id = (struct struct_type_id){ value1, value2, value3 }; Now the RHS of the equals operator is a valid expression, since there is proper context for the compiler to know what is in {...}. In C++11, the syntax is: struct_name_id = struct_type_id{ value1, value2, value3 };
1,705,247
1,705,259
A case where named constants are not needed over magic numbers
Obviously the point of using named constants over magic numbers is for code clarity and for not having to go through code changing numbers throughout. However, what do you do if you just have a number used just once in a function? Say you have a short member function that uses an object's velocity (which we'll say won't change) to calculate its motion, but this is the only function that uses that velocity. Would you... A) Give the class a named static constant to use B) Put a named constant in the function C) Use the magic number but comment it D) Other... I am kind of leaning towards using a magic number and commenting it if the number is ONLY BEING USED ONCE, but I'd like to hear others' thoughts. Edit: Does putting a named constant in a function called many times and assigning to it have performance implications? If it does I guess the best approach would be to put the constant in a namespace or make it a class variable, etc.
Just move it up: void do_something(void) { const float InitialVelocity = 5.0f; something = InitialVelocity; // etc. }
1,705,374
1,723,192
How to capture a string into variable in a recursive function?
I tried to print all the possible combination of members of several vectors. Why the function below doesn't return the string as I expected? #include <iostream> #include <vector> #include <fstream> #include <sstream> using namespace std; string EnumAll(const vector<vector<string> > &allVecs, size_t vecIndex, string strSoFar) { string ResultString; if (vecIndex >= allVecs.size()) { //cout << strSoFar << endl; ResultString = strSoFar; //return ResultString; } for (size_t i=0; i<allVecs[vecIndex].size(); i++) { strSoFar=EnumAll(allVecs, vecIndex+1, strSoFar+allVecs[vecIndex][i]); } ResultString = strSoFar; // Updated but still doesn't return the string. return ResultString; } int main ( int arg_count, char *arg_vec[] ) { vector <string> Vec1; Vec1.push_back("T"); Vec1.push_back("C"); Vec1.push_back("A"); vector <string> Vec2; Vec2.push_back("C"); Vec2.push_back("G"); Vec2.push_back("A"); vector <string> Vec3; Vec3.push_back("C"); Vec3.push_back("G"); Vec3.push_back("T"); vector <vector<string> > allVecs; allVecs.push_back(Vec1); allVecs.push_back(Vec2); allVecs.push_back(Vec3); string OutputString = EnumAll(allVecs,0,""); // print the string or process it with other function. cout << OutputString << endl; // This prints nothing why? return 0; } The expected output is: TCC TCG TCT TGC TGG TGT TAC TAG TAT CCC CCG CCT CGC CGG CGT CAC CAG CAT ACC ACG ACT AGC AGG AGT AAC AAG AAT
Here is an alternate solution. This does not expect you to pass anything but the initial vectors: int resultSize( vector< vector<string> > vector ){ int x=1; for( int i=0;i<vector.size(); i++ ) x *= vector[i].size(); return x; } vector<string> enumAll(const vector< vector<string> > allVecs ) { //__ASSERT( allVecs.size() > 0 ); vector<string> result; if( allVecs.size() == 1 ){ for( int i=0 ; i< allVecs[0].size(); i++){ result.push_back( allVecs[0][i] ); } return result; } for( int i=0; i<allVecs[0].size(); i++ ){ for( int j=0; j<resultSize( vector< vector<string> >(allVecs.begin()+1, allVecs.end() ) ); j++){ result.push_back( allVecs[0][i] + enumAll(vector< vector<string> >(allVecs.begin()+1, allVecs.end() ))[j] );//enumAll on each tempVector is called multiple times. Can be optimzed. } } } Advantage of this method: This is very readable in terms of the recursion. It has easily identifiable recursion base step and also the recursion itself. It works as follows: Each iteration of the recursion enumerates all possible strings from n-1 vectors and the current step simply enumerates them. Disadvantages of this method: 1. enumAll() function is called multiple times returning the same result. 2. Heavy on stack usage since this is not tail recursion. We can fix (1.) by doing the following, but unless we eliminate tail recursion, we cannot get rid of (2.). vector<string> enumAll(const vector< vector<string> > allVecs ) { //__ASSERT( allVecs.size() > 0 ); vector<string> result; if( allVecs.size() == 1 ){ for( int i=0 ; i< allVecs[0].size(); i++){ result.push_back( allVecs[0][i] ); } return result; } const vector< vector<string> > tempVector(allVecs.begin()+1, allVecs.end() ); vector<string> tempResult = enumAll( tempVector );// recurse int size = resultSize( tempVector ); cout << size << " " << tempResult.size() << endl; for( int i=0; i<allVecs[0].size(); i++ ){ for( int j=0; j<size; j++){ result.push_back( allVecs[0][i] + tempResult[j] ); } } }
1,705,582
1,705,603
Private member function that takes a pointer to a private member in the same class
How can I do this? (The following code does NOT work, but I hope it explains the idea.) class MyClass { .... private: int ToBeCalled(int a, char* b); typedef (MyClass::*FuncSig)(int a, char* b); int Caller(FuncSig *func, char* some_string); } I want to call Caller in some way like: Caller(ToBeCalled, "stuff") and have Caller call ToBeCalled with whatever parameters it feels needs passing. If at all possible I want to keep everything encapsulated in the private part of my class. In reality, I'd have about 50 functions like ToBeCalled, so I can't see a way to avoid this. Thanks for any suggestions. :)
You're most of the way there. You're missing the return type from the typedef, it should be typedef int (MyClass::*FuncSig)(int, char*); Now, you just need to use it properly: int Caller(FuncSig func, int a, char* some_string) { return (this->*func)(a, some_string); } You want to pass around plain FuncSig instances, not FuncSig* -- a FuncSig* is a pointer to a pointer to a member function, with an extra unnecessary level of indirection. You then use the arrow-star operator (not its official name) to call it: (object_to_be_called_on ->* func)(args); For non-pointer objects (e.g. objects on the stack, or references to objects), you use the dot-star operator: MyClass x; (x .* func)(args); Also, be wary of operator precedence -- the arrow-star and dot-star operators have lower precedence than function calls, so you need to put in the extra parentheses as I have done above.
1,705,614
1,705,622
Visual C++ saying void function needs to return a value
Visual C++ is saying my void function needs a return value I compiled this on my mac, and it worked perfectly, but now I am trying to compile this with Visual c++ (using windows 7) Heres the build log: Command Lines Creating temporary file "c:\Users\Jonathan\Documents\Visual Studio 2008\Projects\magicsquare\Debug\RSP00000822923000.rsp" with contents [ /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE" /Gm /EHsc /RTC1 /MDd /Fo"Debug\" /Fd"Debug\vc90.pdb" /W3 /c /ZI /TP ".\magicsquare.cpp" ] Creating command line "cl.exe @"c:\Users\Jonathan\Documents\Visual Studio 2008\Projects\magicsquare\Debug\RSP00000822923000.rsp" /nologo /errorReport:prompt" Output Window Compiling... magicsquare.cpp c:\users\jonathan\documents\visual studio 2008\projects\magicsquare\magicsquare.cpp(224) : error C4716: 'check' : must return a value Results Build log was saved at "file://c:\Users\Jonathan\Documents\Visual Studio 2008\Projects\magicsquare\Debug\BuildLog.htm" magicsquare - 1 error(s), 0 warning(s) my function header and function void **check (int **, int); void **check(int **matrix, int size) { //check if first row and last row are the same int rsum = 0, rsum2 = 0; bool rowflag = false; for(int i = 0; i < size; i++) { rsum += *(*(matrix + 0) +i); rsum2 += *(*(matrix + size - 1) +i); } //check if first column and last column are the same int csum = 0, csum2= 0; bool columnflag = false; for(int i = 0; i < size; i++) { csum += *(*(matrix + i) + 0); csum2 += *(*(matrix + i) + size - 1); } //check if diagonals are the same int diagonal = 0, diagonal2 = 0; bool diagonalflag = false; for(int i = 0; i < size; i++) diagonal += *(*(matrix + i) + i); int m = 0; int n = size - 1; while (m <= size - 1) { diagonal2 += *(*(matrix + m) + n); m++; n--; } //if row, column, diagonal are the same if (rsum == rsum2 && rsum2 == csum && csum == csum2 && csum2 == diagonal && diagonal == diagonal2) cout << "This is a Magic Square\n" << endl; else cout << "This is not a Magic Square\n" << endl; } heres the entire code if needed http://pastie.org/691402
Your function is returning a (void **) which is a pointer to a void pointer. To make a void function simply declare it as: void check(int** matrix, int size); Your original code will compile with a warning in C but not in C++. Try this in Visual Studio 2008. Rename your file extension to .c instead of .cpp to force C compilation instead of C++ compilation. It will compile with a warning. But beware, if you ever used the return value of check, it would be garbage. This link has more details: http://pdhut.50megs.com/vczone/articles/diffc/diffc.htm
1,705,724
1,705,754
For C/C++, When is it beneficial not to use Object Oriented Programming?
I find myself always trying to fit everything into the OOP methodology, when I'm coding in C/C++. But I realize that I don't always have to force everything into this mold. What are some pros/cons for using the OOP methodology versus not? I'm more interested in the pros/cons of NOT using OOP (for example, are there optimization benefits to not using OOP?). Thanks, let me know.
Of course it's very easy to explain a million reasons why OOP is a good thing. These include: design patterns, abstraction, encapsulation, modularity, polymorphism, and inheritance. When not to use OOP: Putting square pegs in round holes: Don't wrap everything in classes when they don't need to be. Sometimes there is no need and the extra overhead just makes your code slower and more complex. Object state can get very complex: There is a really good quote from Joe Armstrong who invented Erlang: The problem with object-oriented languages is they’ve got all this implicit environment that they carry around with them. You wanted a banana but what you got was a gorilla holding the banana and the entire jungle. Your code is already not OOP: It's not worth porting your code if your old code is not OOP. There is a quote from Richard Stallman in 1995 Adding OOP to Emacs is not clearly an improvement; I used OOP when working on the Lisp Machine window systems, and I disagree with the usual view that it is a superior way to program. Portability with C: You may need to export a set of functions to C. Although you can simulate OOP in C by making a struct and a set of functions who's first parameter takes a pointer to that struct, it isn't always natural. You may find more reasons in this paper entitled Bad Engineering Properties of Object-Oriented Languages. Wikipedia's Object Oriented Programming page also discusses some pros and cons.
1,706,188
1,706,307
query about a multithreading program
this might a simple query. when we are creating a thread we are passing the (void *)t as an argument to a function PrintHello.we are copying the value in the pointer threadid(typacasting it to long) in tid which is a long variable again.i am confused with the parameter passing. is this a pass by reference or pass by value.over all is this correct? (value *)t. what value does it pass exactly? long t; rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t); void *PrintHello(void *threadid) { long tid; tid = (long)threadid; please help me to avoid my confusion:(
What you are doing is pass by value. It is fine as long as sizeof(T) <= sizeof(void*) for the type T you are trying to pass. If that is not the case, you should to create a T on the heap as it might be out of scope when the created thread tries to access it: T* t = new T(someValue); rc = pthread_create(&threads[t], NULL, PrintHello, (void*)t);
1,706,207
1,717,945
CUrl PUT with xml data
I'm facing a problem with curl as I am unable to issue a PUT request with inline XML data, I'm not sure how its done but I hade a couple of goes on it with different techniques. First I tried using the CURLOPT_UPLOAD as its the default CURL option for PUT and tried to append the xml data manually: typedef map<string, string> headers_t; std::string strCommand = <XMLCOMMAND> PUTRequest(param1, param2, ...) { ... headers_t headers; int nLen = strCommand.length(); stringstream issLen; issLen << nLen; issLen >> strln; curl_easy_setopt(curl, CURLOPT_UPLOAD, true); // HTTP PUT headers.append("Content-Length: "+ strln); // headers.append(strCommand); ... } Then I tried the same method but using the CURLOPT_POSTFIELDS and CURLOPT_POSTFIELDSIZE instead of manually appending the command to the HTTP headers.... did not work. Then I tried customizing the PUT request using the CURLOPT_CUSTOMREQUESToption and setting the parameter to PUT and also manually appending the command and using the POSTFIELDS method. Sadly none worked and now I'm clueless as of what to try next.
When using CURLOPT_UPLOAD, you are appending the XML to the headers of the request rather then to the body where it belongs. You need to use CURLOPT_READDATA (with CURLOPT_READFUNCTION if your XML is not in a file) to provide the XML data when curl asks for it, and also use CURLOPT_INFILESIZE/CURLOPT_INFILESIZE_LARGE so curl can generate a proper 'Content-Length' header (don't append that header manually). If you use CURLOPT_POST, then use CURLOPT_POSTFIELDS and CURL_POSTFIELDSIZE/CURLOPT_POSTFIELDSIZE_LARGE to provide the actual XML data, but then you also have to use CURLOPT_HTTPHEADER to override the default 'Content-Type' header so you can change it from the default value of 'application/x-www-form-urlencoded' to 'text/xml' instead.
1,706,346
19,004,720
__FILE__ macro manipulation handling at compile time
One of the issues I have had in porting some stuff from Solaris to Linux is that the Solaris compiler expands the macro __FILE__ during preprocessing to the file name (e.g. MyFile.cpp) whereas gcc on Linux expandeds out to the full path (e.g. /home/user/MyFile.cpp). This can be reasonably easily resolved using basename() but....if you're using it a lot, then all those calls to basename() have got to add up, right? Here's the question. Is there a way using templates and static metaprogramming, to run basename() or similar at compile time? Since __FILE__ is constant and known at compile time this might make it easier. What do you think? Can it be done?
Using C++11, you have a couple of options. Let's first define: constexpr int32_t basename_index (const char * const path, const int32_t index = 0, const int32_t slash_index = -1) { return path [index] ? ( path [index] == '/' ? basename_index (path, index + 1, index) : basename_index (path, index + 1, slash_index) ) : (slash_index + 1) ; } If your compiler supports statement expressions, and you want to be sure that the basename computation is being done at compile-time, you can do this: // stmt-expr version #define STRINGIZE_DETAIL(x) #x #define STRINGIZE(x) STRINGIZE_DETAIL(x) #define __FILELINE__ ({ static const int32_t basename_idx = basename_index(__FILE__);\ static_assert (basename_idx >= 0, "compile-time basename"); \ __FILE__ ":" STRINGIZE(__LINE__) ": " + basename_idx;}) If your compiler doesn't support statement expressions, you can use this version: // non stmt-expr version #define __FILELINE__ (__FILE__ ":" STRINGIZE(__LINE__) ": " + basename_index(__FILE__)) With this non stmt-expr version, gcc 4.7 and 4.8 call basename_index at run-time, so you're better off using the stmt-expr version with gcc. ICC 14 produces optimal code for both versions. ICC13 can't compile the stmt-expr version, and produces suboptimal code for the non stmt-expr version. Just for completeness, here's the code all in one place: #include <iostream> #include <stdint.h> constexpr int32_t basename_index (const char * const path, const int32_t index = 0, const int32_t slash_index = -1) { return path [index] ? ( path [index] == '/' ? basename_index (path, index + 1, index) : basename_index (path, index + 1, slash_index) ) : (slash_index + 1) ; } #define STRINGIZE_DETAIL(x) #x #define STRINGIZE(x) STRINGIZE_DETAIL(x) #define __FILELINE__ ({ static const int32_t basename_idx = basename_index(__FILE__); \ static_assert (basename_idx >= 0, "compile-time basename"); \ __FILE__ ":" STRINGIZE(__LINE__) ": " + basename_idx;}) int main() { std::cout << __FILELINE__ << "It works" << std::endl; }
1,706,675
1,707,039
file scope and static floats
I've run into an interesting problem in an AI project of mine. I'm trying to format some debug text and something strange is happening. Here's a block of code: float ratio = 1.0f / TIME_MOD; TIME_MOD is a static float, declared in a separate file. This value is modified based off of user input in another class (I have verified that the value is changed while still debugging within the scope of the "input" function), but whenever I try to divide by it in my outer loop I get the same number. (1 divided by the initial value of TIME_MOD). Am I missing something regarding static variables and file scope?
I think there is some confusion with the word "static". We have a keyword static that does different things in different contexts and we use the word "static" to name one of three classes of "storage durations". In some contexts static does not control the storage duration of objects but only "linkage" which is probably the main reason for the confusion. Storage durations A storage duration is a property of an object. The memory of an object with static storage duration is allocated once and once only. Initialization depends on the kind of object and where it is defined. Once it is initialized, it generally stays alive until the execution of main ends. Objects you declare and define at global/namespace scope always have a static storage duration. Objects with automatic storage duration can only be defined inside a block in functions. Such an object is created when execution reaches the definition. This can happen multiple times (recursion) which creates multiple objects. When execution leaves the block the objects are automatically destroyed. Dynamically allocated objects have a dynamic storage duration. In this case the user controls the life-time of the objects via new, new[], delete, delete[] etc. Linkage Internal vs external linkage is about visibility of names across translation units. If you declare something with external linkage you introduce a name that can be used in other translation units as well to refer to the same entity as long as those other TUs contain the proper declaration (usually contained in a header file). If you define something with internal linkage you can't access it from another translation unit by name. You can even define multiple entities with the same name (one per TU) as long as you have no more than one with external linkage. The keyword "static" The effect of static depends on the context: If you declare or define an object at global/namespace scope it is always an object with "static storage duration". The use of the keyword static at global/namespace scope doesn't affect the storage duration at all. Instead, it affects linkage. It declares the entity -- which might be a function as well -- to have internal linkage. So, the storage class specifier has been "misused" to do something completely different: enforce internal linkage. It's sort of the opposite of extern in this context. In C++ you can achieve the same effect with an anonymous namespace. You are encouraged to prefer anonymous namespaces over static to "minimize confusion". static at class scope can be used to declare objects with static storage duration in the scope of the class. There's only one such variable and not one for each object. static at function scope can be used to declare objects with static storage duration that is lazily initialized If you say "static variable" it's not clear what you mean exactly. Do you refer to the "static storage duration" or "internal linkage"? If you want to share a "global" variable across translation units you have to declare it in a header file as an entity with external linkage and define it in exactly one translation unit. Note that the keyword static is not used: // myheader.hpp extern int k; // declaring an int variable with external linkage // foo.cpp #include "myheader.hpp" int k; // defining an int variable with external linkage // bar.cpp #include "myheader.hpp" int main() { return k; }
1,706,762
1,707,671
Which VC++ runtime version do I choose - static or dynamic?
I'm developing a 64-bit in-proc VC++ ATL COM server that basically just redirects all calls to an out-proc COM server. So my COM server basically does nothing. Initially it used the C++ runtime in a DLL (/MD compiler switch). I've noticed that when I deploy it on a clean 64-bit Win2k3 regsvr32 fails with an error: LoadLibrary({fileName}) failed – This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem. Google helps - the problem is that VC++9 runtime is not installed. The problem persists even when msvcr90.dll is in the same directory as my COM server. That as I guess is because of how search for dependent libraries works - it doen't look into the same directory and I need the msvcr90.dll in Windows\System32 or the like. Since this is a complication to my deployment I switched to using the statically linked C++ runtime (/MT compiler switch). Now it deploys fine. The size of the .dll file is 110k only (was 45k) so it doesn't bother me. Now I've heard a lot about how bad it is to mix different versions of C++ runtime in one process - CRT state can be broken, hell can break loose and so on. Do I have to think of this and expect problems from changing /MD to /MT especially since I don't know what version the COM server consumers are using?
As far as I know the Static runtime is deprecated in VS since VS2005. The problem is that the Visual C Runtime is a side by side dll. That is it must be loaded from the c:\windows\winsxs directory. This is why placing it in the same directory is no longer works. The correct solution is to install the correct CRT redistributable on the client system. See http://msdn.microsoft.com/en-us/library/ms235316.aspx for more information This might be the correct redistributable: http://www.microsoft.com/downloads/details.aspx?familyid=BD2A6171-E2D6-4230-B809-9A8D7548C1B6&displaylang=en Installing the correct one will place the runtime dlls in the winsxs directory.
1,706,776
1,706,780
Avoid std::bad_alloc. new should return a NULL pointer
I port a middle-sized application from C to C++. It doesn't deal anywhere with exceptions, and that shouldn't change. My (wrong!) understanding of C++ was (until I learned it the hard way yesterday) that the (default) new operator returns a NULL pointer in case of an allocation problem. However, that was only true until 1993 (or so). Nowadays, it throws a std::bad_alloc exception. Is it possible to return to the old behavior without rewriting everything to using std::nothrow on every single call?
You could overload operator new: #include <vector> void *operator new(size_t pAmount) // throw (std::bad_alloc) { // just forward to the default no-throwing version. return ::operator new(pAmount, std::nothrow); } int main(void) { typedef std::vector<int> container; container v; v.reserve(v.max_size()); // should fail }
1,707,062
1,707,672
How to stop application from executing
I am working on a project to prevent applications from being launched from removable devices. Does anyone out there know how i can do this? Preferrably in C++ on the Windows platform. My aim is to prevent execution of the exe file even if the user double clicks it or even if he tries to launch it from the command line.
Assuming that you wish to stop ANY process launching from a removable drive, this seems to be an application for a shell hook. I wrote the following code over the last half-hour, and it seems to test out OK. Bear in mind that writing a hook is a non-trivial process, and a global hook requires that a DLL be written. This is the relevant guts of the hook DLL: BOOL __declspec(dllexport) __stdcall InstallShellHook () { lpfnHookProc = (HOOKPROC) ShellFunc ; BOOL bRetVal = FALSE; if (hShellHook == NULL) { hShellHook = SetWindowsHookEx (WH_SHELL, lpfnHookProc, hInstance, NULL); return TRUE; } return FALSE; } LRESULT CALLBACK ShellFunc(int nCode, WPARAM wParam, LPARAM lParam) { HWND hWndNew; char szBuff [_MAX_PATH]; char szDrive [_MAX_DRIVE]; switch (nCode) { case HSHELL_WINDOWCREATED: hWndNew = (HWND)wParam; GetWindowModuleFileName (hWndNew, szBuff, _MAX_PATH); _splitpath (szBuff, szDrive, NULL, NULL, NULL); if (GetDriveType (szDrive) == DRIVE_REMOVABLE) { PostMessage (hWndNew, WM_CLOSE, 0, 0); } break; default: break; } return 0; } I have tested this code, installed from a simple dialog testbed, and it allows me to launch any windowed application from my hard drive, but immediately closes any I launch from a USB key. Note that this solution works for all GUI processes (i.e. non-console), but requires that they respond to WM_CLOSE on a top-level window. A more aggressive general solution would probably require you to resolve the hwnd into a hprocess and call TerminateProcess: the solution I have provided is "kinder" (linked DLLs will get unloaded etc), but less general. If you want to know the basics of writing a system-wide hook, you can find them on my website here. Note that the above isn't production-quality code, I hacked it into an old ANSI dll I had laying around, hence the lack of support for Unicode, or anything approaching decent debug capability. It shows the basic idea though.
1,707,164
1,719,116
passing pointers or integral types via performSelector
I am mixing Objective-C parts into a C++ project (please don't argue about that, its cross-platform). I now want to invoke some C++ functions or methods on the correct thread (i.e. the main thread) in a cocoa enviroment. My current approach is passing function pointers to an objective-c instance (derived from NSObject) and do performSelector/performSelectorOnMainThread on it. But the performSelectors expect objects as their arguments, so how would one usually wrap this? Example: typedef void(*FnPtr)(void*); FnPtr fn; [someInstance performSelector:@selector(test:) withObject:fn]; ... where test is declared as: - (void)test:(FnPtr)fn; Have to add that i only started with objective-c this week, so if there is a better way i'd be also glad to hear about it. Also note that i don't have any access to the main loop or any application objects because the project is an browser plug-in (currently only targetting Safari on the mac).
As answered by smorgan here, NSValue is designed as a container for scalar C & Objective-C types: - (void)test:(NSValue*)nv { FnPtr fn = [nv pointerValue]; // ... } // usage: NSValue* nv = [NSValue valueWithPointer:fn]; [someInstance performSelector:@selector(test:) withObject:nv];
1,707,302
1,707,513
Ensuring pointer is not deleted
I've stumbled onto something I can't figure out, so I think I'm missing something in the greater C++ picture. In short, my question is: how to keep a mutable, non-deletable, possibly NULL instance of an object in a class. The longer version is: I have the following scenario: a bunch of classes (which I can change slightly, but not thoroughly refactor), most of which need to use an object. This object, while mutable, is managed by someone else so it must not be deleted. Some of the classes in the bunch do not need such an object - they reuse code from other classes, but through the available parameters supplied to these classes it is guaranteed that even if an object is supplied, it will not be used. The current implementation uses a pointer-to-const-object (const Obj *). This, in turn, means all the object's methods must be const and most fields mutable. This is a messy solution since the fields declared mutable are available for inspection (so quite the opposite of the c++ lite entry here). It also only partially solves the "do-not-delete-this-here" issue (compiler does not complain but a const in front of the object is an indication). If I used a reference to this object, I'd force some callers to create a "dummy" object and provide it to the class they are instantiating. This is also messy, besides being a waste of resources. I cannot create a global object to can stand in for a "NULL" reference due to project restrictions. I feel that the reference is the tool I need, but I cannot refactor the classes involved to such an extent as to have the object disappear from their implementations where it is not used (it can be done, but it is not simple and it would not be fast). So I want to implement something simpler, which will just draw an alarm signal if anyone tries to misuse this object, but keeps my object mutable. The best solution I can think of is using a const-pointer-to-object (Obj * const) - this does not make the compiler complain, but I have my mutable object and a sort-of alarm signal -through the const - in place as well. Does anyone have a better idea ?
I've traditionally seen these kind of scenarios implemented using a shared_ptr/weak_ptr combo. See here. The owner/deleter would get a boost::shared_ptr<T> Your class would get a boost::weak_ptr<T> To reassign the weak ptr, simply reassign the pointer: void MyClass::Reassign(boost::weak_ptr<T> tPtr) { m_tPtr = tPtr; } To use the weak ptr, first check to see if it's still around: void MyClass::Use() { boost::shared_ptr<T> m_temporarySharedPtr = m_tPtr.lock(); if (m_temporarySharedPtr) { //... } } The weak ptr can be made "NULL" by reseting it, or assigning it to an empty shared_ptr void MyClass::MakeNull() { m_tPtr.reset(); }
1,707,575
1,707,619
C++: static function wrapper that routes to member function?
I've tried all sorts of design approaches to solve this problem, but I just can't seem to get it right. I need to expose some static functions to use as callback function to a C lib. However, I want the actual implementation to be non-static, so I can use virtual functions and reuse code in a base class. Such as: class Callbacks { static void MyCallBack() { impl->MyCallBackImpl(); } ... class CallbackImplBase { virtual void MyCallBackImpl() = 0; However I try to solve this (Singleton, composition by letting Callbacks be contained in the implementor class, etc) I end up in a dead-end (impl usually ends up pointing to the base class, not the derived one). I wonder if it is at all possible or if I'm stuck with creating some sort of helper functions instead of using inheritance?
Are any of the parameters passed to the callback function user defined? Is there any way you can attach a user defined value to data passed to these callbacks? I remember when I implemented a wrapper library for Win32 windows I used SetWindowLong() to attach a this pointer to the window handle which could be later retrieved in the callback function. Basically, you need to pack the this pointer somewhere so that you can retrieve it when the callback gets fired. struct CALLBACKDATA { int field0; int field1; int field2; }; struct MYCALLBACKDATA : public CALLBACKDATA { Callback* ptr; }; registerCallback( Callback::StaticCallbackFunc, &myCallbackData, ... ); void Callback::StaticCallbackFunc( CALLBACKDATA* pData ) { MYCALLBACKDATA* pMyData = (MYCALLBACKDATA*)pData; Callback* pCallback = pMyData->ptr; pCallback->virtualFunctionCall(); }
1,708,222
1,723,864
How do I get the PowerBuilder graphicobject for a given HWND handle?
In my (PowerBuilder) application, I'd like to be able to determine the graphicobject object which corresponds to a given window handle. Simply iterating over the Control[] array and comparing the value returned by the Handle() function for each of the child controls doesn't work, since not all objects in my application are children of the main window (consider of login dialogs). Any PowerScript or C/C++ solution would be acceptable. Is there maybe some window message I could send to window handles, and this message is only understood by PowerBuilder windows, which would the respond with their internal object name, or the like?
Is it a requirement to determine the object from the handle, or do you just want to identify an object, for example to know where the code you need to modify is? I made a tool that does the latter, but it uses object focus, rather than window handles. (added 2010-06-21) For windows that aren't children of the main window you could explicitly check each of these window class names with isValid(). Then for each valid window, dig through looking for the handle. This should work as long as you only open one instance of the window class at a time. If you open multiple instances, I think you'll need to add a registration mechanism to the open of those windows so the application has a way to access them.
1,708,317
1,708,759
CertCreateCertificateContext returns ASN1 bad tag value met
I'm loading a .p7b certificate file into memory and then calling CertCreateCertificateContext on it, but it fails with the error "ASN1 bad tag value met.". The call look like this: m_hContext = CertCreateCertificateContext(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, pbCertEncoded, dwCertEncodedLen); This returns NULL and GetLastError() returns the error mentioned above. I created the certificate file by dragging a certificate out of the settings in IE, which then does an automatic export to a file. What am I doing wrong? Thanks!
Try to open your certificate by some asn.1 editor. Probably your certificate has been exported incorrectly or size of the certificate you pass to the api is wrong... Rather the second one option (incorrect cert construction or passing). I found here the info that the encoding you try to use is not fully supported (see possible error values).
1,708,458
1,708,845
Template metaprogram converting type to unique number
I just started playing with metaprogramming and I am working on different tasks just to explore the domain. One of these was to generate a unique integer and map it to type, like below: int myInt = TypeInt<AClass>::value; Where value should be a compile time constant, which in turn may be used further in meta programs. I want to know if this is at all possible, and in that case how. Because although I have learned much about exploring this subject I still have failed to come up with an answer. (P.S. A yes/no answer is much more gratifying than a c++ solution that doesn't use metaprogramming, as this is the domain that I am exploring)
The closest I've come so far is being able to keep a list of types while tracking the distance back to the base (giving a unique value). Note the "position" here will be unique to your type if you track things correctly (see the main for the example) template <class Prev, class This> class TypeList { public: enum { position = (Prev::position) + 1, }; }; template <> class TypeList<void, void> { public: enum { position = 0, }; }; #include <iostream> int main() { typedef TypeList< void, void> base; // base typedef TypeList< base, double> t2; // position is unique id for double typedef TypeList< t2, char > t3; // position is unique id for char std::cout << "T1 Posn: " << base::position << std::endl; std::cout << "T2 Posn: " << t2::position << std::endl; std::cout << "T3 Posn: " << t3::position << std::endl; } This works, but naturally I'd like to not have to specify a "prev" type somehow. Preferably figuring out a way to track this automatically. Maybe I'll play with it some more to see if it's possible. Definitely an interesting/fun puzzle.
1,708,867
1,709,065
check type of element in stl container - c++
how can i get the type of the elements that are held by a STL container?
For containers in general it will be X::value_type. For associative containers it will be X::mapped_type (X::value_type corresponds to pair<const Key,T>). It is according to Chapter 23 of C++ Standard. To check that types are equal you could use boost::is_same. And since C++11 — std::is_same.
1,709,093
1,725,141
Intercepting messages from a child of a child with MFC
I have a CListCtrl class and at the moment when a user selects one of the sub items I am displaying a CComboBox over the subitem which the user can then make a selection from. However I have a problem. When the user has made a selection i need the combo box to disappear (ie intercept CBN_SELCHANGE). The problem is that I need to make the CComboBox a child of the CListCtrl (Otherwise I get weird problems with the list drawing over the combo box even if i set the combo box to be topmost). So the CBN_SELCHANGE message gets sent to the list view which, understandably, ignores it. How can I get the list view to pass that message up to the parent window. Do I really need to derive my own CListCtrl class that simply intercepts the CBN_SELCHANGE message and passes it up to the parent window? Is there a better way to do this than creating an OnWndMsg handler? Thanks for any help! Edit: This code works class CPassThroughListCtrl : public CListCtrl { protected: virtual BOOL OnWndMsg(UINT message, WPARAM wParam, LPARAM lParam, LRESULT* pResult) { if ( message == WM_COMMAND ) { GetParent()->SendMessage( message, wParam, lParam ); } return CListCtrl::OnWndMsg( message, wParam, lParam, pResult ); } public: CPassThroughListCtrl() { }; }; But i'd really like to know if there is a nicer way to do this.
You can subclass CComboBox such that it will handle CBN_CLOSEUP message. Your custom Combo will know about the manager i.e. the object that created it in the first place and will have to destroy it upon close up (top level window or whatever, should be provided as an argument to your custom combobox constructor)... So when you create combobox on a top of the list item you will create instance of this customized combobox instead of the MFC default one. Combobox event handler could look like that: BEGIN_MESSAGE_MAP(CNotifyingComboBox, CComboBox) ON_CONTROL_REFLECT(CBN_CLOSEUP, OnCloseUp) END_MESSAGE_MAP() void CNotifyingComboBox::OnCloseUp() { // _manager is pointer to the object that created this combobox, // and is responsible for its destruction, // should be passed into CNotifyingComboBox cosntructor if( NULL != _manager ) { _manager->OnCloseUpComboBox(this); } }
1,709,194
1,715,756
MySQL/C++ and Prepared Statements: setInt always 0
I'm using the MySQL Connector/C++ library to insert values into a database table. I'm following the examples at http://dev.mysql.com/tech-resources/articles/mysql-connector-cpp.html almost exactly. However, I can't seem to get prepared statements to work with value placeholders. sql::mysql::MySQL_Driver* driver = sql::mysql::MySQL_Driver::Instance(); boost::shared_ptr<sql::Connection> conn(driver->connect("localhost", "", "")); conn->setSchema("TESTDB"); boost::shared_ptr<sql::Statement> stmt(conn->createStatement()); stmt->execute("DROP TABLE IF EXISTS TESTTBL"); stmt->execute("CREATE TABLE TESTTBL (m_id INT)"); boost::shared_ptr<sql::PreparedStatement> pstmt(conn->prepareStatement("INSERT INTO TESTTBL VALUES(?)")); for (int i = 0; i != 10; ++i) { pstmt->setInt(1, i); pstmt->executeUpdate(); // Always inserts 0. } Any ideas on why I can't bind to the prepared statement? The other set* functions have the same result (e.g. if I use setString I get a string '0' in the resulting row).
Recompiling the C++ connector from source fixed this problem. Probably a compiler setting in their pre-built binary that didn't agree with my project. I will talk to MySQL about this. Thanks for the assistance.
1,709,478
1,709,553
Overloading *(iterator + n) and *(n + iterator) in a C++ iterator class?
(Note: I'm writing this project for learning only; comments about it being redundant are... uh, redundant. ;) I'm trying to implement a random access iterator, but I've found very little literature on the subject, so I'm going by trial and error combined with Wikpedias list of operator overload prototypes. It's worked well enough so far, but I've hit a snag. Code such as exscape::string::iterator i = string_instance.begin(); std::cout << *i << std::endl; works, and prints the first character of the string. However, *(i + 1) doesn't work, and neither does *(1 + i). My full implementation would obviously be a bit too much, but here's the gist of it: namespace exscape { class string { friend class iterator; ... public: class iterator : public std::iterator<std::random_access_iterator_tag, char> { ... char &operator*(void) { return *p; // After some bounds checking } char *operator->(void) { return p; } char &operator[](const int offset) { return *(p + offset); // After some bounds checking } iterator &operator+=(const int offset) { p += offset; return *this; } const iterator operator+(const int offset) { iterator out (*this); out += offset; return out; } }; }; } int main() { exscape::string s = "ABCDEF"; exscape::string::iterator i = s.begin(); std::cout << *(i + 2) << std::endl; } The above fails with (line 632 is, of course, the *(i + 2) line): string.cpp: In function ‘int main()’: string.cpp:632: error: no match for ‘operator*’ in ‘*exscape::string::iterator::operator+(int)(2)’ string.cpp:105: note: candidates are: char& exscape::string::iterator::operator*() *(2 + i) fails with: string.cpp: In function ‘int main()’: string.cpp:632: error: no match for ‘operator+’ in ‘2 + i’ string.cpp:434: note: candidates are: exscape::string exscape::operator+(const char*, const exscape::string&) My guess is that I need to do some more overloading, but I'm not sure what operator I'm missing.
First, you need an operator *(void) const. [Edit: based on your existing operator, the following should do: char &operator *(void) const { // bounds checking return *p; } ] Second, you need an operator+(int, exscape::string::iterator). A fairly common way to write this would be (in the iterator class): friend const iterator operator+(const int offset, iterator out) { out += offset; return out; } Note that marking it friend makes it a non-member function, even though it is defined inside the class. You might also want to replace the operator+(int) with a non-member function, operator+(iterator,int), just so that you get the same implicit conversion rules applied to the LHS and RHS of the +. [Another edit: as you point out in your comment, operator+ shouldn't be returning const iterator anyway - just return iterator. So for your code example, you don't actually need operator*()const. But you should have one anyway, because users might want to write code using const-modified instances of your class.] Finally, standard containers with random access iterators (including std::string) define a signed difference_type as a member of the class. int might not be big enough to contain all possible offsets (for example on an LP64 architecture), but ptrdiff_t is a good candidate.
1,709,574
1,711,984
Combine multiple videos into one
I have three videos: a lecture that was filmed with a video camera a video of the desktop capture of the computer used in the lecture and the video of the whiteboard I want to create a final video with those three components taking up a certain region of the screen. Is open-source software that would allow me to do this (mencoder, ffmpeg, virtualdub..)? Which do you recommend? Or is there a C/C++ API that would enable me to create something like that programmatically? EditThere will be multiple recorded lectures in the future. This means that I need a generic/automated solution. I'm currently checking out if I could write an application with GStreamer to do this job. Any comments on that? Solved! I succeeded in doing this with GStreamer's videomixer element. I use the gst-launch syntax to create a pipeline and then load it with gst_parse_launch. It's a really productive way to implement complex pipelines. Here's a pipeline that takes two incoming video streams and a logo image, blends them into one stream and the duplicates it so that it simultaneously displayed and saved to disk. desktop. ! queue ! ffmpegcolorspace ! videoscale ! video/x-raw-yuv,width=640,height=480 ! videobox right=-320 ! ffmpegcolorspace ! vmix.sink_0 webcam. ! queue ! ffmpegcolorspace ! videoscale ! video/x-raw-yuv,width=320,height=240 ! vmix.sink_1 logo. ! queue ! jpegdec ! ffmpegcolorspace ! videoscale ! video/x-raw-yuv,width=320,height=240 ! vmix.sink_2 vmix. ! t. t. ! queue ! ffmpegcolorspace ! ffenc_mpeg2video ! filesink location="recording.mpg" t. ! queue ! ffmpegcolorspace ! dshowvideosink videotestsrc name="desktop" videotestsrc name="webcam" multifilesrc name="logo" location="logo.jpg" videomixer name=vmix sink_0::xpos=0 sink_0::ypos=0 sink_0::zorder=0 sink_1::xpos=640 sink_1::ypos=0 sink_1::zorder=1 sink_2::xpos=640 sink_2::ypos=240 sink_2::zorder=2 tee name="t"
It can be done with ffmpeg; I've done it myself. That said, it is technically complex. That said, again, it is what any other software you might use is going to do in its core essence. The process works like this: Demux audio from source 1 to raw wav Demux audio from source 2 Demux audio from source 3 Demux video from source 1 to MPEG1 Demux video from source 2 Demux video from source 3 Concatenate audio 1 + audio 2 + audio 3 Concatenate video 1 + video 2 + video 3 Mux audio 123 and video 123 into target encode to target format I think what surprises folks is that you can literally concatenate two raw PCM wav audio files, and the result is valid. What really, really surprises people is that you can do the same with MPEG1/h.261 video. Like I've said, I've done it. There are some specifics left out, but it most definately works. My program was done in a bash script with ffmpeg. While I've never used the ffmpeg C API, I don't see why you could not use it to do the same thing. It's a highly educational project to do, if you are inclined. If your goal is just to slap some videos together for a one off project, then maybe using a GUI tool is a better idea.
1,709,718
1,710,287
Am I using a global state here, is there any better way to do this?
I am modifying some legacy code. I have an Object which has a method, lets say doSomething(). This method throws an exception when a particular assertion fails. But due to new requirement, on certain scenarios it is okay to not throw the exception and proceed with the method. Now I am not calling this method directly from the place where I need to ignore the exception. This doSomething() is like an audit method which is called internally from many other methods, lets say method1(), method2(), etc. In the place where I need to ignore the exception, I am calling method1(), now I do not want method1() to throw the exception. So I modified method1() to take a default argument method1(ignoreException = false) and called method1(true). I also modified doSomething() to take the extra argument and method1 just passes the ignoreException back to doSomething(ignoreException). Potentially, I need to change all the methods, method2, method3 etc as well to take this extra argument. On seeing this code, someone suggested that instead of passing this flag around, I can have it as a member variable of the class and then call the setter before calling method1(). Lets say my object is obj, then I should do obj.setIgnoreXXXException(true); obj.method1(); obj.setIgnoreXXXException(false); This seems to me like maintaining some global state and doesnt seem right. But the other way of passing around arguments also seem to be clumsy and I have to change a lot of places (this class has subclasses and some methods are virtual so I need to modify everywhere) Is there a better way of doing this. Since it is legacy and there are no unit tests, I do not want to modify a lot of existing code.
You certainly should be doing this with a function argument, not a member - the choice of whether to ignore the checks is a property of the function invocation, not of the object. Using persistent state to hold a temporary condition will give you two main problems: exception safety - if the function throws an unhandled exception, then your code will leave the "ignore" flag set. reentrancy - calling the function recursively, or from multiple threads, may have unexpected results You can make it exception safe by using a destructor to reset the flag: class IgnoreException { public: explicit IgnoreException(Object &o) : object(o) { object.setIgnoreException(true); } ~IgnoreException() { object.setIgnoreException(false); } private: Object &object; }; void callMethodOneIgnoringException(Object &object) { IgnoreException ignore(object); object.method1(); // the flag is restored here, even if an exception was thrown. } You can't make it reentrant. Any function that accesses persistent state is not reentrant, so the only fix is to use a function argument.
1,709,941
1,709,972
In what order are the aggregated classes deleted?
Let's say I have a basic class A that aggregate B and C: class A { B _b; C _c; } in what order are _b and _c going to be deleted? I've read somewhere that it's the reverse order of their allocation. So I guess in this little example _c is deleted before _b, right? Now if I have a A constructor that looks like that: A::A(): _c(...), _b(...) { } In what order are _b and _c's constructors called? If _b's constructor is indeed called before _c's one (regarding their order in A), then I find it really counter intuitive! In this case what will be the order of destruction? Thanks for your help ! :) (On a side note I seem totally unable to type '}' into Stackoverflow's editor. Had to copy and paste from an external editor !?)
They are destroyed (not deleted) in the reverse order that they were created. It is this that also requires that regardless of how the constructor is written that all the members must be constructed in a consistent order. If each constructor could define the order that the members were constructed, each class instance would have to carry around information on how it was constructed, in order to be able to destruct in reverse order. By defining the order to always be the order that the members were declared in the class definition, the order of construction does not change from constructor to constructor. In your example, first, memory is allocated for the full A class. Next _b is constructed, then _c then A. If A were to have a base class, that would be fully constructed before any of the above. On deletion, the reverse occurs. First A's destructor is called, then _c is destructed, then _b (then any base classes are destructed). Finally the memory for 'A' is freed.
1,710,118
1,710,174
Adding folders to the sidebar of a CFileDialog
Is there any way to add folders to the sidebar in an MFC CFileDialog? (You know, the bar with shortcuts to "Recent Documents", "My Documents", etc. on the left side of the dialog.) Note that I do not mean that I want the user to have to hack the registry or something to permanently add folders to the sidebar system-wide, I'm talking about having my program add a folder to the side-bar for its own file dialogs. So far my research leads me to believe that for XP I can create a custom dialog and replace the side-bar with my own side bar that has the folders in it, but this won't work on Vista (and by extension Windows 7 I'm assuming). So does anyone know a, preferably low pain, way to add folders to that side-bar?
Since Vista there is the IFileDialog which have the AddPlace(...) method. You will need to write a wrapper that will use CFileDialog (On XP) or IFileDialog (Vista and up).
1,710,305
1,718,101
Determine thread which holds the lock on file
I know there is no WINAPI which would do it, but if a thread is hung and holds an open handle of file. how do we determine the thread id and Terminate it within our processes. I'm not talking about releasing file locks in other processes but within my own process. it could also be possible that thread has crashed / terminated without closing the handle.
You cannot determine which thread holds an open handle to a file. Nearly all kernel handles, including file handles, are not associated with a thread but only with a process (mutexes are an exception - they have a concept of an owning thread.) Suppose I have the following code. Which thread "owns" the file handle? void FuncCalledOnThread1() { HANDLE file = CreateFile(...); // Hand off to a background thread. PostWorkItemToOtherThread(FuncCalledOnThread2, file); } void FuncCalledOnThread2(HANDLE file) { DoSomethingWithFile(file); CloseHandle(file); }
1,710,307
1,710,453
How to add a .o on a static library with Eclipse?
I have a .h and a .o that I need to add to a static library in Eclipse. I'm able to add it to an application with the Linker options, but for a static library, I haven't found where to add it in the settings.
G'day, I know it sounds clunky, but you might have to come out of Eclipse and use ar directly. For example: ar -rv my_lib.a new_obj.o ranlib Running ranlib is probably not required anymore with more recent implementations of ar but it's best to run it anyway to make sure that the table has been updated. HTH
1,710,376
1,710,398
Convert files of any types to a file with c strings
Please suggest a small command-line utility (for Windows) to convert files from particular directory to a valid c file. Maybe it can be done just with batch commands? The resulting file should look like this: static const unsigned char some_file[] = { /* some_file.html */ 0x2f, 0x70, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x65, 0x73, 0x2e, 0x73, 0x68, 0x74, 0x6d, 0x6c, 0, 0x25, 0x21, 0x3a, 0x20, 0x2f, 0x68, 0x65, 0x61, 0x64, 0x65 } static const unsigned char some_other_file[] = { /* some_other_file.png*/ 0x2f, 0x34, 0x30, 0x34, 0x2e, 0x68, 0x74, 0x6d, 0x6c, 0, 0x3c, 0x68, 0x74, 0x6d, 0x6c, 0x3e, 0xa, 0x20, 0x20, 0x3c } P.S. Please don't suggest Perl and Python ports. They are too heavy for this task. P.P.S. May be someone knows more customizable utility than bin2h, but less heavy and complex than awt? Which can parse several files and put them into one C. Also specifing custom variable names (using some kind of an index file) whould be great. So it can be added to the build process.
Bin2h will do this. Bin2h - Win32 binary to C header file converter A Win32 command-line utility for converting a binary file into a C header file, representing the contents of that file as a block of data. I don't believe the input file has to be a binary file.
1,710,447
1,710,462
String in scientific notation C++ to double conversion
I've got a database filled up with doubles like the following one: 1.60000000000000000000000000000000000e+01 Does anybody know how to convert a number like that to a double in C++? Is there a "standard" way to do this type of things? Or do I have to roll my own function? Right now I'm doing sth like this: #include <string> #include <sstream> int main() { std::string s("1.60000000000000000000000000000000000e+01"); std::istringstream iss(s); double d; iss >> d; d += 10.303030; std::cout << d << std::endl; } Thanks!
Something like this? This would be the "C++" way of doing it... #include <sstream> using namespace std; // ... string s = "1.60000000000000000000000000000000000e+01"; istringstream os(s); double d; os >> d; cout << d << endl; Prints 16.
1,710,660
1,710,819
Know any good c++ support vector machine (SVM) libraries?
Do you know of any good c++ svm libraries out there I tried libsvm http://www.csie.ntu.edu.tw/~cjlin/libsvm/ but so far I'm not flabbergasted. I have also heard of SVMLight and TinySVM. Have you tried them ? Any new players ? Thanks !
SVMTorch (support vector machines for large-scale regression problems) implemented in the torch machine learning library. mySVM - based on the optimization algorithm of SVM-Light. A comprehensive list of SVM libraries can be found here.
1,710,828
1,711,559
C#: problem loading C++ DLL
In my code, I can load "MessageBoxA" from user32.dll and use it, but if I try to load and use a function from my DLL, I get a crash. My C# code: [DllImport("SimpleDLL.dll")] static extern int mymean(int a, int b, int c); [DllImport("user32.dll")] static extern int MessageBoxA(int hWnd, string msg, string caption, int type); [...] this works MessageBoxA(0, "Hello, World!", "This is called from a C# app!", 0); this crashes int mean = mymean(12, 14, 16); And my C++ DLL code: SimpleDLL.cpp: extern "C" _declspec(dllexport) int mymean(int x, int y, int z) { return (x + y + z) / 3; } SimpleDLL.def: LIBRARY "SimpleDLL" mymean SimpleDLL.dll is copied to the same folder as the .exe I compile from C# code. Using dependency walker, I can see that all necessary DLLs to load SimpleDLL.dll are present.
Turns out my C# app was 64-bit (which is C# visual studio default) and my C++ DLL was 32-bit (which is C++ visual studio default). Thanks for the tip to check the exception type, it was a badimageformatexception. Sorry - total C# newbie!
1,711,058
1,711,090
sizeof(*this) in header only constructor implementation
Whilst the 'standards' are to prefer a sizeof(typename), are there any instances where the sizeof(*this) is more error-prone or somehow undesirable? I cannot see any at the first glance, but if yes, why with a short explanation would be helpful.
The only reason I can think of to avoid sizeof(*this) is that it could be misunderstood as the size of the actual object (e.g., a derived class).
1,711,161
1,711,197
Destructor of a concrete class
Guideline #4 link text, states: A base class destructor should be either public and virtual, or protected and nonvirtual. Probably I'm missing something, but what if I just create a concrete class, that is not designed to be used as base class. Should I declare it's destructor public and virtual? By this I'm implicitly declate that my class is "ready to be used as base class", while this is not necessary true.
The link text specifically says"A base class destructor should be"... The guidelines are only meant for a class which is designed to be used as a base class. If you are making a single, concrete class that will not be used as a base class, you should leave the public constructor non-virtual.
1,711,426
1,722,766
Design methods for multiple serialization targets/formats (not versions)
Whether as members, whether perhaps static, separate namespaces, via friend-s, via overloads even, or any other C++ language feature... When facing the problem of supporting multiple/varying formats, maybe protocols or any other kind of targets for your types, what was the most flexible and maintainable approach? Were there any conventions or clear cut winners? A brief note why a particular approach helped would be great. Thanks. [ ProtoBufs like suggestions should not cut it for an upvote, no matter how flexible that particular impl might be :) ]
Reading through the already posted responses, I can only agree with a middle-tier approach. Basically, in your original problem you have 2 distinct hierarchies: n classes m protocols The naive use of a Visitor pattern (as much as I like it) will only lead to n*m methods... which is really gross and a gateway towards maintenance nightmare. I suppose you already noted it otherwise you would not ask! The "obvious" target approach is to go for a n+m solution, where the 2 hierarchies are clearly separated. This of course introduces a middle-tier. The idea is thus ObjectA -> MiddleTier -> Protocol1. Basically, that's what Protocol Buffers does, though their problematic is different (from one language to another via a protocol). It may be quite difficult to work out the middle-tier: Performance issues: a "translation" phase add some overhead, and here you go from 1 to 2, this can be mitigated though, but you will have to work on it. Compatibility issues: some protocols do not support recursion for example (xml or json do, edifact does not), so you may have to settle for a least-common approach or to work out ways of emulating such behaviors. Personally, I would go for "reimplementing" the JSON language (which is extremely simple) into a C++ hierarchy: int strings lists dictionaries Applying the Composite pattern to combine them. Of course, that is the first step only. Now you have a framework, but you don't have your messages. You should be able to specify a message in term of primitives (and really think about versionning right now, it's too late once you need another version). Note that the two approaches are valid: In-code specification: your message is composed of primitives / other messages Using a code generation script: this seems overkill there, but... for the sake of completion I thought I would mention it as I don't know how many messages you really need :) On to the implementation: Herb Sutter and Andrei Alexandrescu said in their C++ Coding Standards Prefer non-member non-friend methods This applies really well to the MiddleTier -> Protocol step > creates a Protocol1 class and then you can have: Protocol1 myProtocol; myProtocol << myMiddleTierMessage; The use of operator<< for this kind of operation is well-known and very common. Furthermore, it gives you a very flexible approach: not all messages are required to implement all protocols. The drawback is that it won't work for a dynamic choice of the output protocol. In this case, you might want to use a more flexible approach. After having tried various solutions, I settled for using a Strategy pattern with compile-time registration. The idea is that I use a Singleton which holds a number of Functor objects. Each object is registered (in this case) for a particular Message - Protocol combination. This works pretty well in this situation. Finally, for the BOM -> MiddleTier step, I would say that a particular instance of a Message should know how to build itself and should require the necessary objects as part of its constructor. That of course only works if your messages are quite simple and may only be built from few combination of objects. If not, you might want a relatively empty constructor and various setters, but the first approach is usually sufficient. Putting it all together. // 1 - Your BOM class Foo {}; class Bar {}; // 2 - Message class: GetUp class GetUp { typedef enum {} State; State m_state; }; // 3 - Protocl class: SuperProt class SuperProt: public Protocol { }; // 4 - GetUp to SuperProt serializer class GetUp2SuperProt: public Serializer { }; // 5 - Let's use it Foo foo; Bar bar; SuperProt sp; GetUp getUp = GetUp(foo,bar); MyMessage2ProtBase.serialize(sp, getUp); // use GetUp2SuperProt inside
1,711,490
1,961,432
Returning a C++ class to Java via JNI
I'm currently using both C++ and Java in a project and I'd like to be able to send an object which is contained in C++ to my Java interface in order to modify it via a GUI and then send the modification back in C++. So far I've been returning either nothing, an int or a boolean to Java via the JNI interface. This time I have to send an object through the interface. I have made similar class definition available both in C++ and in Java. I'd like to know how I'd go about creating the object so that I can use it in Java. In C++ I have: JNIEXPORT MyObject JNICALL Java_ca_X_Y_Z_C_1getMyObject(JNIEnv* env, jclass, jint number); This function would get called by Java in order to get the object from the C++ side (the object is contained in a singleton, easily accessible). On the Java end, I do a simple call to this method, MyObject anObject = C_getMyObject(3); which should return me the newly created object. Java currently returns me a UnsatisfiedLinkError when I do the actual call. What is wrong?
Here's the solution I opted to use: First, I would create a similar object in Java. Then, from C++ I would instanciate it and pass it all the values. (C++) clazz = env->FindClass("java/lang/Integer"); jmethodID method = env->GetMethodID(clazz, "<init>", "(I)V"); return env->NewObject(clazz, method, (jint)anInteger); But then I realised this wasn't very portable and was a bit too complicated. Instead, I decided to return a string that Java would parse and use to initialize the object on its side. (JAVA) String aString = "valuesoftheobject"; MyObject myObject(aString); MyObject would have a constructor which takes a string. I believe the solution is simple and effective.