question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
3,009,824
3,010,033
Void in main and keeping Dos program from dying
Possible Duplicate: Difference between void main and int main? Alright, so I'm using bloodshed complier, first thing I should note is I'm using a 2001 edition C++ for the absolute beginner, was there any changes to C++ since 2001 that would effect the validity of this book? I ask because I know php has php5 and now php6 but I haven't seen any C++03. Now for the reason I asked that, in this code it uses, void main (void) why would I want an argument to be void? what does this do. But when I run the void main (void) in my compiler it says that main must have a "int" before it. So I can't have "void" main (void); Also, once the code runs through, as long as there isn't a "cin" the program closes. Is this normal behavior, is there a better way to stop this besides making a cin at the end of my program?
What there have been since 2001 are changes to C++ compilers, which on the whole are much pickier about how standards-conformant your C++ must be before they accept it. For example, gcc has gone from 2.95 or so all the way to 4.4.2. Earlier compilers may have let you slide with this form of main, as they would several old C-isms that are not proper C++, but it's not the language that's changed in this case (at least, as far as the standard goes). Having said that: yes, C++ has changed, and is changing, though not quite yet at the official standards level. Different compilers support those changes to different extents. I don't think you're likely to be impacted by them, but you may want to be aware of them at any rate. See: C++ TR1 C++0x, the forthcoming standard As far as how to end your program. I recommend a simple "return 0;" at the point in main where you want to exit – or use an exit code other than 0 if you want to exit with an error. You can omit the return, though, and many examples do this, though I personally think it's bad style. I understand you're using cin to pause the application before it exits. This isn't required for C++ apps in general, it's just a convenience for running the app in the manner you are. It's OK for examples, but you'd definitely want to avoid that for a real application.
3,009,911
3,010,026
operator overloading and inheritance
I was given the following code: class FibHeapNode { //... // These all have trivial implementation virtual void operator =(FibHeapNode& RHS); virtual int operator ==(FibHeapNode& RHS); virtual int operator <(FibHeapNode& RHS); }; class Event : public FibHeapNode { // These have nontrivial implementation virtual void operator=(FibHeapNode& RHS); virtual int operator==(FibHeapNode& RHS); virtual int operator<(FibHeapNode& RHS); }; class FibHeap { //... int DecreaseKey(FibHeapNode *theNode, FibHeapNode& NewKey) { FibHeapNode *theParent; // Some code if (theParent != NULL && *theNode < *theParent) { //... } //... return 1; } }; Much of FibHeap's implementation is similar: FibHeapNode pointers are dereferenced and then compared. Why does this code work? (or is it buggy?) I would think that the virtuals here would have no effect: since *theNode and *theParent aren't pointer or reference types, no dynamic dispatch occurs and FibHeapNode::operator< gets called no matter what's written in Event.
You must be a bit confused about dynamic dispatch. It is often said that "dynamic dispatch occurs only when you make a call through a pointer or through a reference". Formally speaking, this statement is totally bogus and misleading. Dynamic dispatch in C++ happens always when you call a virtual function, with one and only one exception: dynamic dispatch is disabled when you use a fully qualified-name of the target function. For example: some_pointer->SomeClass::some_function(); // fully-qualified name In the above code the call will be dispatched statically, even if some_function is a virtual function. From the language point of view, there's no other ways to avoid the dynamic dispatch, i.e. in all other cases all calls to virtual functions are dispatched dynamically. What you use: a pointer, a reference, an immediate object - does not matter, the dispatch is still dynamic. Where you are calling the function from: from constructor/destructor or from somewhere else - does not matter, the dispatch is still dynamic. And I repeat: this is how things are from the point of view of the C++ language itself. This is how an "abstract C++ machine" works. What happens in practice though, is that in many cases the dynamic dispatch can be replaced with static dispatch, because the compiler knows the dynamic type of the object in advance, at the compile-time and, consequently, knows the target of the dispatch. In such cases it makes more sense to call the target function directly, instead of going through the costlier dynamic dispatch mechanism. Yet, this is nothing else than just an optimization. Some people, unfortunately, mistake that optimization for language-mandated behavior, coming up with such meaningless statements as "dynamic dispatch occurs only when you make a call through a pointer or through a reference". In your specific case the dispatch is dynamic. Since in your case the compiler does not know the dynamic types of the objects involved, it cannot optimize it into a static dispatch, which is why your code "works as intended". P.S. Anticipating the possible questions about something I said above: Dynamic dispatch for calls made from constructors/destructors is limited by the current dynamic type of the object, which is why in straightforward cases it is possible (and easy) for the compiler to optimize them into a static dispatch. This is the reason for another popular urban legend that states that virtual calls from constructors/destructors are resolved statically. In reality, in general case they are resolved dynamically, as they should (again, observing the current dynamic type of the object).
3,010,048
3,010,074
Posix equivalent of LocalAlloc(LMEM_ZEROINIT, size)
I have code which works on windows, that calls LocalAlloc as follows: LocalAlloc(LMEM_ZEROINIT, size) I need the equivalent malloc or calloc call to get this to work on Unix systems, through Mono. Simple answer?
From what I understand it just allocs zeroed memory, so a calloc(1, size) should suffice to allocate size zeroed bytes.
3,010,160
3,010,264
C++: Assign L"" string to WCHAR[]?
I have a WCHAR[]: WCHAR foo[200]; I want to copy values into it: if (condition) { foo = L"bar"; } else { foo = L"odp"; } What is the best way to do this?
Depending on exactly what you need to do, you could change the type of foo: const WCHAR *foo; if (condition) { foo = L"bar"; } else { foo = L"odp"; } This is fine if don't need to append any more data to foo.
3,010,201
3,010,242
Should I use C(99) booleans ? ( also c++ booleans in c++ ?)
I haven't done much c programming but when I do when I need a false I put 0 when I want true I put 1, (ex. while(1)), in other cases I use things like "while(ptr)" or "if(x)". Should I try using C99 booleans, should I recommend them to others if I'm helping people new to programming learn c basics(thinking of cs 1?? students)? I'm pretty sure the Visual Studio compiler supports c99 bools, but do a lot of projects (open source and c apps in industry) compile for c89? If I don't use C bools should I at least do something like #define TRUE 1 #define FALSE 0? Also what about c++ Booleans (for c++)?
In C++ there is no reason to not use it. In C, i only use int for this task, without any #define or something like that. Variable-names like isDefinition are clear enough to indicate what's going on, in my opinion. Of course, there is nothing wrong with defining your own bool or using the ones of <stdbool.h>.
3,010,305
3,010,871
Programmatically selecting file in explorer
In my application I can programmatically open explorer and select a file using the following code: void BrowseToFile(LPCTSTR filename) { CString strArgs; strArgs = _T("/select,\""); strArgs += filename; strArgs += _T("\""); ShellExecute(0, _T("open"), _T("explorer.exe"), strArgs, 0, SW_NORMAL); } My problem is that if I call this function a second time with a different file, but in the same folder, the selection in explorer does not change to the new file, but remains on the previous file. For example, if I call my function with C:\path\to\file1.txt, a new explorer window will open and file1.txt will be selected. If I call my function a second time with C:\path\to\file2.txt, the existing explorer window will be activated, but the selection will still be on file1.txt. Is there a way to force explorer to update the selection or a better way to accomplish this? EDIT: The behavior mentioned above was on Windows XP. It seems the behavior on Vista / Win7 is different. Each call will open a new instance of explorer and select the file. My main goal is to replicate the Visual Studio option to Open Containing Folder of a document. This feature in Visual Studio behaves the same on XP, Vista, and Win7. It will not create a new instance if another instance with the same folder is already open, but it will update the selection to the new file. If anybody knows how Visual Studio accomplishes this I would love to know about it.
Found the answer to my question. I need to use the shell function SHOpenFolderAndSelectItems. Here is the code for the function if anybody is ever interested: void BrowseToFile(LPCTSTR filename) { ITEMIDLIST *pidl = ILCreateFromPath(filename); if(pidl) { SHOpenFolderAndSelectItems(pidl,0,0,0); ILFree(pidl); } }
3,010,339
3,010,366
C++: Cannot convert from foo& to foo*
I have a method: odp(foo& bar); I'm trying to call it: foo baz; odp(&baz); I get a compiler error: error C2664: "odp" cannot convert parameter 1 from 'foo *' to 'foo &' What am I doing wrong? Aren't I passing in a reference to baz? UPDATE: Perhaps I have a misconception about the relationship between pointers and references. I thought that they were the same, except references couldn't be null. Is that incorrect?
When you apply the unary & operator to an object, you get a pointer to that object, not a reference. You need a reference in this case. In order to initialize a reference parameter, you don't need to apply any operators at all: an lvalue object can immediately be used by itself to initialize a reference of the appropriate type. The informal synonymity between the notions of "pointer" and "reference" (as in "pass by pointer" and "pass by reference") is specific to C language. But in C++ they mean two completely different things.
3,010,347
3,050,828
C++ Builder and Excel Automation, where to get started?
I want to dynamically create and populate an excel spreadsheet with C++ builder 2009, but I'm not entirely sure how to go about it. Searching the web, I've narrowed it down to using OLE Automation. Moreover, I'm looking for a document or programming tutorial that can get me started. Is there a simple programming tutorial that also thoroughly explains the concepts of OLE automation?
To open an excel spreadsheet: Variant excelApp = Unassigned; //EOleSysError is thrown if GetActiveObject does not succeed. i.e //if Excel is not currently open. try { excelApp = Variant::GetActiveObject("Excel.Application"); } catch(EOleSysError& e) { excelApp = Variant::CreateObject("Excel.Application"); //open excel } excelApp.OlePropertySet("ScreenUpdating", true); To get the current cell pointer: Variant excelCell = excelSheet.OlePropertyGet("Cells"); To add values to excel: // create a vararray of 5 elements starting at 0 int bounds[2] = {0, 4}; Variant variantValues = VarArrayCreate(bounds, 1, varVariant); variantValues.PutElement(5, 0); variantValues.PutElement(5, 1); variantValues.PutElement(5, 2); variantValues.PutElement(5, 3); variantValues.PutElement(5, 4); Variant cellRange = excelCell.OlePropertyGet( "Range", excelCell.OlePropertyGet("Item", rowindex, columnindex), // start cell excelCell.OlePropertyGet("Item", rowindex2, columnindex2) // finishing cell ); // place array into excel cellRange.OlePropertySet( "Value", excelApp.OleFunction("Transpose", variantValues) ); I hope this gets you started, you will probably need to include vcl.h and comobj.hpp.
3,010,483
3,010,601
Trouble with wstringstream
I have a wstringstream: wstringstream sstream; AlterSstream(sstream); wstringstream bar_stream; bar_stream << sstream; bar_stream << "foo"; MessageBoxW( NULL, bar_stream.str().c_str(), L"subject", MB_OK ); This outputs a long string that looks nothing like what I put in it in AlterSstream(): 00000000002CEC58foo AlterSstream: void AlterSstream(wstringstream& outStream) { outStream << "odp"; } Why is this happening? If I print out sstream directly, it works fine, but printing out bar_stream creates the problem. I'm guessing that the << operator doesn't work the way I think it does between two streams? UPDATE: Sorry, I had left a bit of code out originally. It is fixed above.
There is no overload to copy from stream to stream. You need to change the line: bar_stream << sstream; to: bar_stream << sstream.str();
3,010,550
3,010,908
Hardcoding the resources in application
I have some code which shows a simple dialog box and handles user action (written using plain WinAPI). // Display dialog and handle user action LRESULT choice = DialogBoxParam(NULL, MAKEINTRESOURCE(AP_IDD_DIALOG), NULL, (DLGPROC)DialogCallback, NULL); Is there any way to hardcode the resource file dialog.rc, which is used to build the dialog ?(I would like to get rid of .rc files and I'm pretty sure there is a way, yet I don't know what it is :) Edit Also, does someone have any ideas on converting existing .rc files into hardcoded resources? Is this possible?
I'm surprised I couldn't find an existing app to do this sort of thing, enough hits on google with people trying to do this. Ok, so the DLGTEMPLATE is a variable length blob of data, normally you let the dialog function pull it from the resource bundle for you, but instead you want to store it in your program. You need to change your static lib to have a new function to decode some 'blob' back into the dlgtemplate, and you need to generate the blob. (or add the blob in your code without decoding which I don't want to think about right now) The following code will give you the DLGTemplate data you need to imbed in your app. (cut from larger project) HGLOBAL LoadResourceImpl(wchar_t *resource, wchar_t *type) { HRSRC handle = FindResource(hInstance, resource,type); if (handle) { HGLOBAL hResource = LoadResource(hInstance, handle); if (hResource) return LockResource(hResource); } return 0; } DLGTEMPLATE * LoadDialog(wchar_t *resource) { return (DLGTEMPLATE *) LoadResourceImpl(resource,RT_DIALOG); } DLGTEMPLATE * LoadDialog(int resource) { return (DLGTEMPLATE *) LoadResourceImpl(MAKEINTRESOURCE(resource),RT_DIALOG); } Make an app that includes your resource - use the appropriate LoadDialog to get the data. Now "write out" that blob in a format to include in your app - step 1 - find out how much data there is by traversing the structure to find the total size including all the controls (control count is in DLGTEMPLATE::cdit) step 2 - convert the data to something you can compile into your code - like HEX Add to your static library a new 'HEX' to DLGTEMPLATE method and the hex string you made using the other app.
3,010,791
3,010,982
Mutability design patterns in Objective C and C++
Having recently done some development for iPhone, I've come to notice an interesting design pattern used a lot in the iPhone SDK, regarding object mutability. It seems the typical approach there is to define an immutable class NSFoo, and then derive from it a mutable descendant NSMutableFoo. Generally, the NSFoo class defines data members, getters and read-only operations, and the derived NSMutableFoo adds on setters and mutating operations. Being more familiar with C++, I couldn't help but notice that this seems to be a complete opposite to what I'd do when writing the same code in C++. While you certainly could take that approach, it seems to me that a more concise approach is to create a single Foo class, mark getters and read-only operations as const functions, and also implement the mutable operations and setters in the same class. You would then end up with a mutable class, but the types Foo const*, Foo const& etc all are effectively the immutable equivalent. I guess my question is, does my take on the situation make sense? I understand why Objective-C does things differently, but are there any advantages to the two-class approach in C++ that I've missed? Or am I missing the point entirely? Not an overly serious question - more for my own curiosity than anything else.
Objective-C is too dynamic. In C++ const-qualification is enforced at compile-time, and any violations of const-qualification at runtime (such as modifying a const-qualified object through a non-const-qualified pointer) is undefined behaviour. It is partly the same as the reason why there are no private methods in Objective-C. You are free to send whatever message you want to any object. The runtime dispatch takes an object and a message, and resolves a method implementation to invoke. if const qualified objects could only invoke const qualified methods, it would completely ruin the dynamic nature of Objective-C and Foundation because such a check would need to be done at runtime (first check would determine whether the message being sent resolves to a const-qualified implementation for that specific instance, and another check to determine whether the instance itself was const-qualified). Consider this theoretical example: NSArray *mutableArray = [[NSArray alloc] init]; NSString *mutableString = @"I am a mutable string"; const NSString *immutableString = @"I am immutable because I am const-qual'd"; [mutableArray addObject:mutableString]; [mutableArray addObject:immutableString]; // what happens?! // and what happens here (both immutable and mutable strings would respond // to the same selectors because they are the same class): [mutableArray makeObjectsPerformSelector:@selector(aMutableOperation)]; Suddenly you lose dynamics. As it is now, mutable and immutable objects can sit together in an immutable or mutable collection. Having a mutable subclass keeps the dynamic nature of Objective-C and keeps the runtime simple. There was a similar topic a while ago about private methods.
3,010,913
3,010,924
Is there an existing template for a new C++ Open Source project
I want to start a new C++ (Qt) Open Source project and I'm wondering if there is an existing template somewhere for files usually found in an Open Source project but that are not purely source code (README, LICENSE, CHANGELOG, etc.) I could probably find a popular Open Source project for inspiration but if there is some existing generic templates, I will use that instead. Thanks.
One place to look might be the implementation of the GNU Hello program. It includes all the standard template files expected by the GNU coding guidelines. You may, of course, choose to follow another set of guidelines than GNU's.
3,011,005
3,011,009
What is operator<< <> in C++?
I have seen this in a few places, and to confirm I wasn't crazy, I looked for other examples. Apparently this can come in other flavors as well, eg operator+ <>. However, nothing I have seen anywhere mentions what it is, so I thought I'd ask. It's not the easiest thing to google operator<< <>( :-)
<> after a function name (including an operator, like operator<<) in a declaration indicates that it is a function template specialization. For example, with an ordinary function template: template <typename T> void f(T x) { } template<> void f<>(int x) { } // specialization for T = int (note that the angle brackets might have template arguments listed in them, depending on how the function template is specialized) <> can also be used after a function name when calling a function to explicitly call a function template when there is a non-template function that would ordinarily be a better match in overload resolution: template <typename T> void g(T x) { } // (1) void g(int x) { } // (2) g(42); // calls (2) g<>(42); // calls (1) So, operator<< <> isn't an operator.
3,011,036
3,011,051
need to get computer speaking to a cell phone
i have this super manual: http://www.arib.or.jp/IMT-2000/V710Dec08/5_Appendix/R99/27/27005-320.pdf i dont understand whether it is for every phone or just a certain subset i would like to know what i need to get started to have my computer speak to the phone i am ready to write in c#, c++, or what ever they need has anyone had experience writing AT commands?
basically you need a cable, and most often you talk to it through a serial port which is basically what something like http://www.microsoft.com/downloads/details.aspx?familyid=06a4f997-7f69-4891-8929-37b9041924a2&displaylang=en does
3,011,253
3,011,897
Why is my slot not being called?
I have this class: class CustomEdit : public QTextEdit { Q_GADGET public: CustomEdit(QWidget* parent); public slots: void onTextChanged (); }; CustomEdit::CustomEdit(QWidget* parent) : QTextEdit(parent) { connect( this, SIGNAL(textChanged()), this, SLOT(onTextChanged())); } void CustomEdit::onTextChanged () { // ... do stuff } The onTextChanged method is never called when I type text into the edit control. What am I missing?
All classes that contain signals or slots must mention Q_OBJECT at the top of their declaration. They must also derive (directly or indirectly) from QObject. Try using Q_OBJECT
3,011,271
3,012,858
How to get width and height of directshow webcam video stream
I found a bit of code that gets me access to the raw pixel data from my webcam. However I need to know the image width, height, pixel format and preferably the data stride(pitch, memory padding or whatever you want to call it) if its ever gonna be something other than the width * bytes per pixel #include <windows.h> #include <dshow.h> #pragma comment(lib,"Strmiids.lib") #define DsHook(a,b,c) if (!c##_) { INT_PTR* p=b+*(INT_PTR**)a; VirtualProtect(&c##_,4,PAGE_EXECUTE_READWRITE,&no);\ *(INT_PTR*)&c##_=*p; VirtualProtect(p, 4,PAGE_EXECUTE_READWRITE,&no); *p=(INT_PTR)c; } // Here you get image video data in buf / len. Process it before calling Receive_ because renderer dealocates it. HRESULT ( __stdcall * Receive_ ) ( void* inst, IMediaSample *smp ) ; HRESULT __stdcall Receive ( void* inst, IMediaSample *smp ) { BYTE* buf; smp->GetPointer(&buf); DWORD len = smp->GetActualDataLength(); //AM_MEDIA_TYPE* info; //smp->GetMediaType(&info); HRESULT ret = Receive_ ( inst, smp ); return ret; } int WINAPI WinMain(HINSTANCE inst,HINSTANCE prev,LPSTR cmd,int show){ HRESULT hr = CoInitialize(0); MSG msg={0}; DWORD no; IGraphBuilder* graph= 0; hr = CoCreateInstance( CLSID_FilterGraph, 0, CLSCTX_INPROC,IID_IGraphBuilder, (void **)&graph ); IMediaControl* ctrl = 0; hr = graph->QueryInterface( IID_IMediaControl, (void **)&ctrl ); ICreateDevEnum* devs = 0; hr = CoCreateInstance (CLSID_SystemDeviceEnum, 0, CLSCTX_INPROC, IID_ICreateDevEnum, (void **) &devs); IEnumMoniker* cams = 0; hr = devs?devs->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, &cams, 0):0; IMoniker* mon = 0; hr = cams->Next (1,&mon,0); // get first found capture device (webcam?) IBaseFilter* cam = 0; hr = mon->BindToObject(0,0,IID_IBaseFilter, (void**)&cam); hr = graph->AddFilter(cam, L"Capture Source"); // add web cam to graph as source IEnumPins* pins = 0; hr = cam?cam->EnumPins(&pins):0; // we need output pin to autogenerate rest of the graph IPin* pin = 0; hr = pins?pins->Next(1,&pin, 0):0; // via graph->Render hr = graph->Render(pin); // graph builder now builds whole filter chain including MJPG decompression on some webcams IEnumFilters* fil = 0; hr = graph->EnumFilters(&fil); // from all newly added filters IBaseFilter* rnd = 0; hr = fil->Next(1,&rnd,0); // we find last one (renderer) hr = rnd->EnumPins(&pins); // because data we are intersted in are pumped to renderers input pin hr = pins->Next(1,&pin, 0); // via Receive member of IMemInputPin interface IMemInputPin* mem = 0; hr = pin->QueryInterface(IID_IMemInputPin,(void**)&mem); DsHook(mem,6,Receive); // so we redirect it to our own proc to grab image data hr = ctrl->Run(); while ( GetMessage( &msg, 0, 0, 0 ) ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } }; Bonus points if you can tell me how get this thing not to render a window but still get me access to the image data.
That's really ugly. Please don't do that. Insert a pass-through filter like the sample grabber instead (as I replied to your other post on the same topic). Connecting the sample grabber to the null renderer gets you the bits in a clean, safe way without rendering the image. To get the stride, you need to get the media type, either through ISampleGrabber or IPin::ConnectionMediaType. The format block will be either a VIDEOINFOHEADER or a VIDEOINFOHEADER2 (check the format GUID). The bitmapinfo header biWidth and biHeight defines the bitmap dimensions (and hence stride). If the RECT is not empty, then that defines the relevant image area within the bitmap. I'm going to have to wash my hands now after touching this post.
3,011,274
3,011,307
Antialiasing algorithm?
I have textures that i'm creating and would like to antialias them. I have access to each pixel's color, given this how could I antialias the entire texture? Thanks
The basic method for anti-aliasing is: for a pixel P, sample the pixels around it. P's new color is the average of its original color with those of the samples. You might sample more or less pixels, change the size of the area around the pixel to sample, or randomly choose which pixels to sample. As others have said, though: anti-aliasing isn't really something that's done to an image that's already a bitmap of pixels. It's a technique that's implemented in the 2D/3D rendering engine.
3,011,291
3,011,398
Replacement compiler for Qt Creator?
I like Qt Creator as an IDE, but the built-in compiler is slower than dirt. Can I replace it, and if so, with what? Developing on Windows but targeting multiple Mac as well.
By default on Windows the compiler is mingw, a port of GCC. Qt also contains support for the Visual Studio compilers, which you can switch to. The only full-fledged C++ compiler on Macintosh is GCC. C++, especially with template heavy code, is slow to compile. There is no avoiding this. In my experience, Visual Studio is not appreciably faster on complex code bases over GCC.
3,011,345
3,011,551
C++ online Role Playing Game (RPG)
So I've been learning C++ and SDL to make some basic 2d games. I want to create a game sort of like World of Warcraft but a 2D version. I want it to be on-line and use a database or something to start data like amount of Gold, HP, etc. I was wondering though, if I do this in SDL, would it still work on-line or would the user have to download SDL themselves to play? I just want a game like this but be able to play it with some friends, just for learning purposes you know. I was also looking at DirectX because everyone has that on windows pretty much. Anyways much help is appreciated, thanks!
No offense, but an RPG is definately the last thing a new programmer should attempt to create. They are the most time, resource, and skill intensive style of game one could possibly try to create. I speak from experience here and can say that RPGs are huge time sinks, even for experienced game studios. At best, you might get a basic map working before you run out of time and patience. If you want a game you can play with your friends, why not multiplayer tic-tac-toe or even artillery or something similiar. You'll have more success and may actually have something to show your friends when you are done.
3,011,409
3,013,086
Sparse constrained linear least-squares solver
This great SO answer points to a good sparse solver for Ax=b, but I've got constraints on x such that each element in x is >=0 an <=N. Also, A is huge (around 2e6x2e6) but very sparse with <=4 elements per row. Any ideas/recommendations? I'm looking for something like MATLAB's lsqlin but with huge sparse matrices. I'm essentially trying to solve the large scale bounded variable least squares problem on sparse matrices: EDIT: In CVX: cvx_begin variable x(n) minimize( norm(A*x-b) ); subject to x <= N; x >= 0; cvx_end
You are trying to solve least squares with box constraints. Standard sparse least squares algorithms include LSQR and more recently, LSMR. These only require you to apply matrix-vector products. To add in the constraints, realize that if you are in the interior of the box (none of the constraints are "active"), then you proceed with whatever interior point method you chose. For all active constraints, the next iteration you perform will either deactivate the constraint, or constrain you to move along the constraint hyperplane. With some (conceptually relatively simple) suitable modifications to the algorithm you choose, you can implement these constraints. Generally however, you can use any convex optimization package. I have personally solved this exact type of problem using the Matlab package CVX, which uses SDPT3/SeDuMi for a backend. CVX is merely a very convenient wrapper around these semidefinite program solvers.
3,011,412
3,011,467
Command prompt print dialog command
Is there any way a C++ commandline program on Windows can produce a graphical GUI print dialog for printing to a printer, just like usual GUI programs? I've combed through this webpage and it seems there are only commands that print files in the background to a pre-determined printer.
Command-line applications in Windows still have full access to everything that GUI-mode applications do (the only difference is they start out with a console, whereas GUI-mode applications do not). So you can still call all of the regular printing functions from GDI.
3,011,421
3,011,435
Qt 101: Why can't I use this class?
I have experience with C++ but I've never really used Qt before. I'm trying to connect to a SQLite database, so I found a tutorial here and am going with that. In the QtCreator IDE, I went to Add New --> C++ Class and in the header file pasted in the header the header from that link and in the .cpp file I pasted the source. My main.cpp looks like this: #include <QtGui/QApplication> #include "mainwindow.h" #include "databasemanager.h" #include <qlabel.h> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); DatabaseManager db(); QLabel hello("nothing..."); if(db.openDB()){ // Line 13 hello.setText("Win!"); } else{ hello.setText("Lame!"); } hello.resize(100, 30); hello.show(); return a.exec(); } And I'm getting this error: main.cpp:13: error: request for member 'openDB' in 'db', which is of non-class type 'DatabaseManager()' Can anyone point me in the right direction? I know "copypaste" code isn't good, I just wanted to see if I could get DB connectivity working and I figured something like this would be simple... thanks for the help.
Change the DatabaseManager line to: DatabaseManager db; You're declaring a local function called db that takes no parameters and returns a DatabaseManager object when you provide the ();
3,011,486
3,013,364
Help with GetGlyphOutline function(WinAPI)
I want to use this function to get contours and within these contours, I want to get cubic bezier. I think I have to call it with GGO_BEZIER. What puzzles me is how the return buffer works. "A glyph outline is returned as a series of one or more contours defined by a TTPOLYGONHEADER structure followed by one or more curves. Each curve in the contour is defined by a TTPOLYCURVE structure followed by a number of POINTFX data points. POINTFX points are absolute positions, not relative moves. The starting point of a contour is given by the pfxStart member of the TTPOLYGONHEADER structure. The starting point of each curve is the last point of the previous curve or the starting point of the contour. The count of data points in a curve is stored in the cpfx member of TTPOLYCURVE structure. The size of each contour in the buffer, in bytes, is stored in the cb member of TTPOLYGONHEADER structure. Additional curve definitions are packed into the buffer following preceding curves and additional contours are packed into the buffer following preceding contours. The buffer contains as many contours as fit within the buffer returned by GetGlyphOutline." I'm really not sure how to access the contours. I know that I can change a pointer another type of pointer but i'm not sure how I go about getting the contours based on this documentation. Thanks
I have never used this API myself, but after reading the MSDN documentation I would think it works like this: First you have to call GetGlyphOutline with the lpvBuffer parameter set to NULL. Then the function will return the required size of the buffer. You'll then have to allocate a buffer with that size, then call the function again with lpvBuffer set to your newly created buffer. If you take a look at the documentation for TTPOLYGONHEADER it says: Each TTPOLYGONHEADER structure is followed by one or more TTPOLYCURVE structures. So, basically you have to do something like this: BYTE* pMyBuffer = NULL; ... TTPOLYGONHEADER* pPolyHdr = reinterpret_cast<TTPOLYGONHEADER*>(pMyBuffer); TTPOLYCURVE* pPolyCurve = reinterpret_cast<TTPOLYCURVE*>(pMyBuffer + sizeof(TTPOLYGONHEADER)); Then, check the pPolyCurve->cpfx member which contains the number of POINTFX structures. Then you can iterate all the points by doing something like this: for (WORD i = 0; i < pPolyCurve->cpfx: ++i) { pCurve->apfx[i].x; pCurve->apfx[i].y; } Since the TTPOLYGONHEADER doesn't tell you how many TTPOLYCURVE structures are in the buffer, I guess you'll have to keep track of that yourself by subtracting the size of the individual structures from the size of your buffer and keep going until you reach 0. Please excuse any potential errors as I didn't test this myself :)
3,011,515
3,011,524
Vector iterators in for loops, return statements, warning, c++
I have three questions regarding a homework assignment for C++. The goal was to create a simple palindrome method. Here is my template for that: #ifndef PALINDROME_H #define PALINDROME_H #include <vector> #include <iostream> #include <cmath> template <class T> static bool palindrome(const std::vector<T> &input) { std::vector<T>::const_iterator it = input.begin(); std::vector<T>::const_reverse_iterator rit = input.rbegin(); for (int i = 0; i < input.size()/2; i++, it++, rit++) { if (!(*it == *rit)) { return false; } } return true; } template <class T> static void showVector(const std::vector<T> &input) { for (std::vector<T>::const_iterator it = input.begin(); it != input.end(); it++) { std::cout << *it << " "; } } #endif Regarding the above code, can you have more than one iterator declared in the first part of the for loop? I tried defining both the "it" and "rit" in the palindrome() method, and I kept on getting an error about needing a "," before rit. But when I cut and paste outside the for loop, no errors from the compiler. (I'm using VS 2008). Second question, I pretty much just brain farted on this one. But is the way I have my return statements in the palindrome() method ok? In my head, I think it works like, once the *it and *rit do not equal each other, then the function returns false, and the method exits at this point. Otherwise if it goes all the way through the for loop, then it returns true at the end. I totally brain farted on how return statements work in if blocks and I tried looking up a good example in my book and I couldn't find one. Finally, I get this warnings: \palindrome.h(14) : warning C4018: '<' : signed/unsigned mismatch Now is that because I run my for loop until (i < input.size()/2) and the compiler is telling me that input can be negative? Thanks!
can you have more than one iterator declared in the first part of the for loop? Yes, but they both have to be of the same type, so you can't declare both a const_iterator and a const_reverse_iterator. is the way I have my return statements in the palindrome() method ok? Yes, though why not just compare *it != *rit? palindrome.h(14) : warning C4018: '<' : signed/unsigned mismatch i is signed; std::vector::size() returns an unsigned value. If i was unsigned, you would not get this warning. As a suggestion, though: it might be simpler to use two forward iterators. Initialize one to .begin() and the other to .end() - 1. You can then increment the first and decrement the second and your loop test simply becomes it1 < it2. Something like the following (completely untested) for-loop: for (iterator it1(v.begin()), it2(v.end() - 1); it1 < it2; ++it1, --it2) This way you no longer need the separate i counter and comparisons; everything is done with iterators.
3,011,564
3,012,301
How can i list and watch all global variables on watch windows of visual studio (for c++)?
When stopped at a breakpoint on main(), i can manually add name of a global variables to watch windows, but what i want is how to show a list of all global variables, because i'm using an external library, which contains many static things. Is it possible? Thanks in advance!
Is the problem that you don't know the global variable names? Or is the problem that you want to look at many global variables and don't want to type them over and over again in the watch window? For the moment I assume the second. I also assume that your external library is a .LIB library and not a .DLL. You could write a class that contains one member for every global variable you want to watch, make it a reference, and construct an instance of the class at startup, assigning the global variables to the reference members, like this: class MyGlobalVariableClass { public: MyGlobalVariableClass() : m_var1(globalVariable1OfExternalLibrary) , m_var2(globalVariable2OfExternalLibrary) {} private: long &m_var1; double &m_var2; }; MyGlobalVariableClass myGlobalVariableInstance; Now you can just enter myGlobalVariableInstance in the watch window, expand it, and you will see all its members, and thus all the global variables. This trick assumes that you know all the names of the global variables. If you don't, you could try to use DUMPBIN to investigate the contents of the LIB of the external library, and try to deduct the variable names from the output of DUMPBIN.
3,011,980
3,012,149
Initialize Pointer Through Function
I was browsing my teacher's code when I stumbled across this: Order* order1 = NULL; then order1 = order(customer1, product2); which calls Order* order(Customer* customer, Product* product) { return new Order(customer, product); } This looks like silly code. I'm not sure why, but the teacher initialized all pointers to NULL instead of declaring them right away(looking at the code it's entirely possible, but he chose not to). My question is: is this good or acceptable code? Does the function call have any benefits over calling a constructor explicitely? And how does new work in this case? Can I imagine the code now as kind of like: order1 = new Order(customer, product);
Init to NULL [edit] since there's a valid discussion, I've changed the order of the options a bit to emphasize the recommended option. Variables should be declared as local and as late as possible, and initialized immediately. Thus, the most common pattern is: Order * order1 = order(...); just before order1 is required. If there is any reason to separate the declaration of order1 from the instantiation, like this: Order * order1; // Oh no! not initialized! // ... some code order1 = order(...); order1 should be initialized to NULL, to prevent common bugs that occur with uninitialized variables, easily introduced when // some code changes. Factory method Again, there's some more change resilence here: the requirements for instantiating an Order may change. There are two scenarios I can think of right off top of my head: (1) Validation that can't be done by Order's constructor. Order may come from a 3rd party library and can't be changed, or instantiation needs to add validation that isn't within the scope of Order: Order* order(Customer* customer, Product* product) { // Order can't validate these, since it doesn't "know" the database database.ValidateCustomer(customer); // throws on error database.ValidateProduct(product); // throws on error return new Order(customer, product); } (2) You may need an order that behaves differently. class DemoOrder : public Order { ... } Order* order(Customer* customer, Product* product) { if (demoMode) return new DemoOrder(customer, product); // doesn't write to web service else return new Order(customer, product); } However, I wouldn't make this a general pattern blindly.
3,012,169
3,012,628
Lots of pointer casts in QGraphicsView framework and performance
Since most of the convenience functions of QGraphicsScene and QGraphicsItem (such as items(), collidingItems(), childItems() etc.) return a QList you're forced to do lots of qgraphicsitem_cast or static_cast and QGraphicsItem::Type() checks to get hold of the actual items when you have lots of different type of items in the scene. I thought doing lots of subclass casts were not a desirable coding style, but I guess in this case there are no other viable way, or is there? QList<QGraphicsItem *> itemsHit = someItem->collidingItems(Qt::IntersectsItemShape); foreach (QGraphicsItem *item, itemsHit) { if (item->type() == QGraphicsEllipseItem::type()) { QGraphicsEllipseItem *ellipse = qgraphicsitem_cast<QGraphicsEllipseItem *>(item); // do something } else if (item->type() == MyItemSubclass::type()) { MyItemSubClass *myItem = qgraphicsitem_cast<MyItemSubClass *>(item); // do something } // etc } The above qgraphicsitem_cast could be replaced by static_cast since correct type is already verified. When doing lots of these all the time (very dynamic scene), will the numerous casting affect performance beyond the normal if-else evaluation?
The performance overhead is mostly prepaid; it's the result of the overhead of having the .type() member. It might be efficient to retrieve the item->type() once. You know it doesn't change, but chances are the compiler doesn't. [edit] Also, if you really have a lot of types, it could be worthwhile to introduce some intermediate types. eg. if (dynamic_cast<MyGraphicsInterMediateType*>(item)) {/* check those types */} else {/* other types */}
3,012,181
3,012,210
When should we use * , & , . , ->?
Why are we using * character when we are creating button but we aren't adding it to app instance? #include <QApplication> #include <QPushButton> int main(int argc,char *argv[]) { QApplication app(argc,argv); QPushButton *button = new QPushButton("Button Text"); QObject::connect(button,SIGNAL(clicked()),&app,SLOT(quit())); button->show(); return app.exec(); } When should we use *, &, ., ->?
new returns a pointer, hence the * is used here to define button as a pointer-to-QPushButton, The & is used to reference (get the address of) app, which is then passed to connect. button->show(); is equivalent to: (*button).show(); This is all basic C (except new) and C++ covered in any introductory book.
3,012,243
3,014,190
boost::asio buffer impossible to convert parameter from char to const mutable_buffer&
visual studio tells me "error C2664: 'boost::asio::mutable_buffer::mutable_buffer(const boost::asio::mutable_buffer&)': impossible to convert parameter 1 from 'char' to 'const boost::asio::mutable_buffer&' at line 163 of consuming_buffers.hpp" I am unsure of why this happen nor how to solve it(otherwise I wouldn't ask this ^^') but I think it could be related to those functions.. even tough I tried them in another project and everything worked fine... but I can hardly find what's different so... here comes code that could be relevant, if anything useful seems to be missing I'll be glad to send it. packets are all instances of this class. class CPacketBase { protected: const unsigned short _packet_type; const size_t _size; char* _data; public: CPacketBase(unsigned short packet_type, size_t size); ~CPacketBase(); size_t get_size(); const unsigned short& get_type(); virtual char* get(); virtual void set(char*); }; this sends a given packet template <typename Handler> void async_write(CPacketBase* packet, Handler handler) { std::string outbuf; outbuf.resize(packet->get_size()); outbuf = packet->get(); boost::asio::async_write( _socket , boost::asio::buffer(outbuf, packet->get_size()) , handler); } this enable reading packets and calls a function that decodes the packet's header(unsigned short) and resize the buffer to send it to another function that reads the real data from the packet template <typename Handler> void async_read(CPacketBase* packet, Handler handler) { void (CTCPConnection::*f)( const boost::system::error_code& , CPacketBase*, boost::tuple<Handler>) = &CTCPConnection::handle_read_header<Handler>; boost::asio::async_read(_socket, _buffer_data , boost::bind( f , this , boost::asio::placeholders::error , packet , boost::make_tuple(handler))); } and this is called by async_read once a packet is received template <typename Handler> void handle_read_header(const boost::system::error_code& error, CPacketBase* packet, boost::tuple<Handler> handler) { if (error) { boost::get<0>(handler)(error); } else { // Figures packet type unsigned short packet_type = *((unsigned short*) _buffer_data.c_str()); // create new packet according to type delete packet; ... // read packet's data _buffer_data.resize(packet->get_size()-2); // minus header size void (CTCPConnection::*f)( const boost::system::error_code& , CPacketBase*, boost::tuple<Handler>) = &CTCPConnection::handle_read_data<Handler>; boost::asio::async_read(_socket, _buffer_data , boost::bind( f , this , boost::asio::placeholders::error , packet , handler)); } }
Based on this line of code... unsigned short packet_type = *((unsigned short*) _buffer_data.c_str()); ...I'm guessing you are using a std::string as the type for _buffer_data and attempting to read data into it using boost::asio::async_read. You can't do that (see my answer here for an explanation: How to asynchronously read to std::string using Boost::asio?) You could try using one of the factory overloads of boost::asio::buffer and using a POD type such as char *. For example: char * _buffer_data = new char[packet->get_size()-2]; boost::asio::async_read( _socket, boost::asio::buffer(_buffer_data, packet->get_size()-2), //.... (I've not tested this, but in theory it should create a mutable buffer wrapping a raw char array that has at most packet->get_size()-2 bytes. Makes sense...) You could also try using a boost::shared_array<char> instead, but I'm not sure that can be implicitly converted to a mutable buffer either, so you'd have to roll your own "mutable buffer." Note that since boost::asio::async_read is a template function, the second parameter's type is not strictly defined, and can actually be anything that adheres to the mutable buffers concept. See this page for more info on that: http://www.boost.org/doc/libs/1_43_0/doc/html/boost_asio/reference/MutableBufferSequence.html
3,012,351
3,012,411
How to know if a QLineEdit got focus?
I want to be able to know if in the QLineEdit it was a click. So I guess I should reimplement the following function(??): void QLineEdit::focusInEvent ( QFocusEvent * e ) [virtual protected] How should I do that? Also, please tell me how to use focusInEvent() function in order to know if QLineEdit myEdit; object got focus. EDIT: I have written the following function: bool LoginDialog::eventFilter(QObject *target, QEvent *event) { if (target == m_passwordLineEdit) { if (event->type() == QEvent::FocusIn) { if(checkCapsLock()) { QMessageBox::about(this,"Caps Lock", "Your caps lock is ON!"); } return true; } } return QDialog::eventFilter(target, event); } And have registered m_passwordLineEdit in LoginDialog class constructor like this: m_passwordLineEdit->installEventFilter(this); And it's falling into an infinite loop of MessageBox-es. Please help me to resolve this situation. Actually I would like to implemet this function with a pop-up window (not with a QMessageBox). Is it OK to use QLabel for that need?
Something like that: class YourWidget : public QLineEdit { Q_OBJECT protected: void focusInEvent(QFocusEvent* e); }; In the .cpp file: void YourWidget::focusInEvent(QFocusEvent* e) { if (e->reason() == Qt::MouseFocusReason) { // The mouse trigerred the event } // You might also call the parent method. QLineEdit::focusInEvent(e); } You can find the list of all possible reasons on this page.
3,012,406
3,012,412
C++ interview question involving class pointers
Lets say there is a base class pointer which is pointing to a base class object: baseclass *bptr; bptr= new baseclass; now if i do bptr= new derived; what is the problem here?
The obvious answer is that you're leaking the original base class object.
3,012,559
3,012,890
How to create combobox with bitmaps in Win32?
I wanted to create a custom combo box like this (as in MS Word), Are there any Win32 API calls (I can't use MFC) to get this job done, (like ChooseColor() or ChooseFont()? If there aren't any, can anyone please tell me how to do this? Thanks you. Regards, EDIT: Creating the Owner-Drawn Dialog Box!! Is this the only way ? http://msdn.microsoft.com/en-us/library/bb775794%28VS.85%29.aspx#creating_square_meal
You have some options to solve your problem: All common controls supports WM_SETFONT, so if you find a Font which has all line elements which you need, you can change font of the combobox control and fill items with corresponding textes. There are ComboBoxEx control which combines images with textes (see http://msdn.microsoft.com/en-us/library/bb775738(VS.85).aspx). Be careful, what part of items will be selected (just try it). If you can a little change your requirements to the combobox control you will be able to use this. You can use owner-draw combo-box. Then you are absolutely free, but your code can be a liitle longer and you should be more carful if you works with non-standard color shema of windows or a non-default theams. I'll recommend you use functions GetSysColor in this case. You should deceide youself whay way is the best for your project requirements.
3,012,606
3,012,648
hash_map and stdext:: hash_map?
Under the visual C++, we have " hash_map" and "hash_set". In g++, we have " stdext::hash_map" and " stdext::hash_set". Is there any difference in terms of their respective performance or other factors?
None of those are standards. They were just there to fill a need. Concerning the performances, I have no idea, but I guess they're really similar. What existed in TR1, and will be included in C++1X is unordered_map and unordered_set They say they changed the name to avoid any confusion with previous non-standard implementations. http://www2.research.att.com/~bs/C++0xFAQ.html#std-unordered
3,012,839
3,012,867
Compilation errors calling find_if using a functor
We are having a bit of trouble using find_if to search a vector of pairs for an entry in which the first element of the pair matches a particular value. To make this work, we have defined a trivial functor whose operator() takes a pair as input and compares the first entry against a string. Unfortunately, when we actually add a call to find_if using an instance of our functor constructed using a temporary string value, the compiler produces a raft of error messages. Oddly (to me, anyway), if we replace the temporary with a string that we've created on the stack, things seem to work. Here's what the code (including both versions) looks like: typedef std::pair<std::string, std::string> MyPair; typedef std::vector<MyPair> MyVector; struct MyFunctor: std::unary_function <const MyPair&, bool> { explicit MyFunctor(const std::string& val) : m_val(val) {} bool operator() (const MyPair& p) { return p.first == m_val; } const std::string m_val; }; bool f(const char* s) { MyFunctor f(std::string(s)); // ERROR // std::string str(s); // MyFunctor f(str); // OK MyVector vec; MyVector::const_iterator i = std::find_if(vec.begin(), vec.end(), f); return i != vec.end(); } And here's what the most interesting error message looks like: /usr/include/c++/4.2.1/bits/stl_algo.h:260: error: conversion from ‘std::pair, std::allocator >, std::basic_string, std::allocator > >’ to non-scalar type ‘std::string’ requested Because we have a workaround, we're mostly curious as to why the first form causes problems. I'm sure we're missing something, but we haven't been able to figure out what it is.
This is the most vexing parse. You can do: MyFunctor f(s); or MyFunctor f((std::string(s))); The original declares a function f. f takes a single argument, a pointer to a function taking an argument s and returning std::string.
3,013,154
3,013,159
How to call operator<< on "this" in a descendant of std::stringstream?
class mystream : public std::stringstream { public: void write_something() { this << "something"; } }; This results in the following two compile errors on VC++10: error C2297: '<<' : illegal, right operand has type 'const char [10]' error C2296: '<<' : illegal, left operand has type 'mystream *const ' Judging from the second one, this is because what this points at can't be changed, but the << operator does (or at least is declared as if it does). Correct? Is there some other way I can still use the << and >> operators on this?
mystream *const means that this is a constant pointer to a non-constant object. The problem is that you're trying to stream-insert into a pointer -- you must insert into a stream. Try the following. *this << "something";
3,013,286
3,013,435
GetAdaptersInfo (c++)function not working on vista and windows 7
i am using GetAdaptersInfo on windows xp to retrieve mac address.its working well on xp but neither on vista nor on windows 7. Is GetAdaptersInfo supported by windows 7 and vista. if no what api should i use to get mac address
DWORD GetAdaptersInfo( PIP_ADAPTER_INFO pAdapterInfo, PULONG pOutBufLen ); How did you allocate memory for pAdapterInfo? Seems that there is some issue with stack allocation of this [in] parameter. See this
3,013,354
3,013,394
How do I refactor code into a subroutine but allow for early exit?
There's a really obvious refactoring opportunity in this (working) code. bool Translations::compatibleNICodes(const Rule& rule, const std::vector<std::string>& nicodes) { bool included = false; // Loop through the ni codes. for(std::vector<std::string>::const_iterator iter = nicodes.begin(); iter != nicodes.end(); ++iter) { // Match against the ni codes of the rule if(rule.get_ni1() == *iter) { // If there's a match, check if it's flagged include or exclude const std::string flag = rule.get_op1(); // If include, code is included unless a later rule excludes it if(flag == "INCLUDE"){ included = true; } // If exclude, code is specifically excluded else if(flag == "EXCLUDE"){ return false; } } if(rule.get_ni2() == *iter) { const std::string flag = rule.get_op2(); if(flag == "INCLUDE"){ included = true; } else if(flag == "EXCLUDE"){ return false; } } if(rule.get_ni3() == *iter) { const std::string flag = rule.get_op3(); if(flag == "INCLUDE"){ included = true; } else if(flag == "EXCLUDE"){ return false; } } if(rule.get_ni4() == *iter) { const std::string flag = rule.get_op4(); if(flag == "INCLUDE"){ included = true; } else if(flag == "EXCLUDE"){ return false; } } if(rule.get_ni5() == *iter) { const std::string flag = rule.get_op5(); if(flag == "INCLUDE"){ included = true; } else if(flag == "EXCLUDE"){ return false; } } } return included; } I want to turn it to something like: bool Translations::compatibleNICodes(const Rule& rule, const std::vector<std::string>& nicodes) { bool included = false; // Loop through the ni codes. for(std::vector<std::string>::const_iterator iter = nicodes.begin(); iter != nicodes.end(); ++iter) { // Match against the ni codes of the rule included |= matchNICode(rule.get_ni1(), rule.get_op1); included |= matchNICode(rule.get_ni2(), rule.get_op2); included |= matchNICode(rule.get_ni3(), rule.get_op3); included |= matchNICode(rule.get_ni4(), rule.get_op4); included |= matchNICode(rule.get_ni5(), rule.get_op5); } return included; } bool Translations::matchNICode(const std::string& ni, const std::string& op) { if(ni == *iter) { if(op == "INCLUDE"){ return true; } else if(op == "EXCLUDE"){ /*Return worse than false*/ } } return false; } The problem is that I can't get around the problem that I want to exit early if it's an exclude statement. Note that I can't change the structure of the Rule class. Any advice?
Obviously the code would be much cleaner and simpler, if you could iterate through the ni and op members of Rule in a loop. If you can't refactor Rule, maybe you could create a wrapper around it to achieve this goal. If you have a single method with such code, I wouldn't bother though. IMO this would only pay off if you can eliminate the duplicated code in several similar methods.
3,013,406
3,013,446
Can I disable min, max in STL?
I use one library which is very important and untouchable. The problem is that library declare min, max function, so when I include STL header in project, they conflict. I want to disable min, max function in STL (like #define NOMNMAX) if I could. If I can't, what would be solution? Important : Sorry, It's not Macro. Two functions are template functions. like template<T> T min(const T& a, const T& b) { a < b ? a : b; } Thanks, in advance.
The min and max functions are defined in the std namespace, so this code should not compile: #include <algorithm> int main() { int n = min( 1, 2 ); } If it does, your Standard Library is non-compliant. Also, your important and untouchable library should be declaring it's functions in a namespace. If it isn't. complain loudly to the vendor. Edit: As these functions are presumably in a header file, you can touch them. So a hack would be to remove the templates from the header and replace them with the following: using std::min; using std::max; though why the writers of the library felt the need to define these templates is anyone's guess.
3,013,743
3,013,764
Do I need multiple template specializations if I want to specialize for several kinds of strings?
For example: template<typename T> void write(T value) { mystream << value; } template<> void write<const char*>(const char* value) { write_escaped(mystream, value); } template<> void write<char*>(char* value) { write_escaped(mystream, value); } template<> void write<const std::string&>(const std::string& value) { write_escaped(mystream.c_str(), value); } This looks like I'm doing it wrong, especially the two variants for const and non-const char*. However I checked that if I only specialize for const char * then passing a char * variable will invoke the non-specialized version, when called like this in VC++10: char something[25]; strcpy(something, "blah"); write(something); What would be the proper way of doing this?
You did it the proper way. char * and const char * are two distinct typenames, they require each their own specialization.
3,013,757
3,013,796
Are there possible approaches to map signal handling (c library) into a c++ exception?
I have a c++ application linked against some c libraries. Are there possible approaches to encapsulate the signal handling in a C++ class, so it could be handled as a c++ exception?
You can't and if you could a lot of things would break. What you should do is set a flag in the signal handler, periodically check in your code and throw an exception when you detect the flag is set. Such an approach is similar to how threads get interrupted in Boost.Threads, which I strongly suggest you study.
3,013,909
3,014,715
What arguments do I pass to the client when running the boost::asio sockets examples
I am learning how to use the boost asio libraries and I am using the UDP examples on visual studio 2008. I have compiled and run the server application(name udp_server.exe). I have tried to run the client application but is does connect to the server. How do I specify the host and service name to the application for it to connect. I have specified the machine name but I get an error "No connection could be made because the target machine actively refused it". Are there some prerequisite setup I need to perform on my Windows 7 machine to get the examples to work?
Assuming that you are referring to the "Daytime.4 - A synchronous UDP daytime client" example, the server's host name is passed as argv[1] (the first command-line parameter) to the udp::resolver::query ctor. As you can see from the docs, the port is passed as the 3rd parameter to the ctor. This parameter can be a string representation of the port number or a "service name". Quoting the docs about this: On POSIX systems, service names are typically defined in the file /etc/services. On Windows, service names may be found in the file c:\windows\system32\drivers\etc\services. If all this seems ok and connection still fails, check the firewall settings on the server to make sure that it allows connections on the chosen port.
3,013,926
3,014,304
How to write a custom predicate for multi_index_containder with composite_key?
I googled and searched in the boost's man, but didn't find any examples. May be it's a stupid question...anyway. So we have the famous phonebook from the man: typedef multi_index_container< phonebook_entry, indexed_by< ordered_non_unique< composite_key< phonebook_entry, member<phonebook_entry,std::string,&phonebook_entry::family_name>, member<phonebook_entry,std::string,&phonebook_entry::given_name> >, composite_key_compare< std::less<std::string>, // family names sorted as by default std::greater<std::string> // given names reversed > >, ordered_unique< member<phonebook_entry,std::string,&phonebook_entry::phone_number> > > > phonebook; phonebook pb; ... // look for all Whites std::pair<phonebook::iterator,phonebook::iterator> p= pb.equal_range(boost::make_tuple("White"), my_custom_comp()); How should my_custom_comp() look like? I mean it's clear for me then it takes boost::multi_index::composite_key_result<CompositeKey> as an argumen (due to compilation errors :) ), but what is CompositeKey in that particular case? struct my_custom_comp { bool operator()( ?? boost::multi_index::composite_key_result<CompositeKey> ?? ) const { return blah_blah_blah; } }; Thanks in advance.
It should look like composite_key_compare. For your case (non-template version): typedef composite_key< phonebook_entry, member<phonebook_entry,std::string,&phonebook_entry::family_name>, member<phonebook_entry,std::string,&phonebook_entry::given_name> > my_comp_type_t; struct my_custom_comp { bool operator()( const boost::tuple<const char*>& x, const boost::multi_index::composite_key_result<my_comp_type_t>& y ) const { return false; // should return something instead of false } bool operator()( const boost::multi_index::composite_key_result<my_comp_type_t>& y, const boost::tuple<const char*>& x ) const { return false; // should return something instead of false } };
3,013,989
3,014,057
Problems compiling an external library on linux
So I am trying to compile the libssh2 library on linux, but when I try to compile the example it comes up with a lot of errors, and even though I include the headerfile it asks for, it still asks for it. Here are the error messages and the resulting messages: ~/ gcc -include /home/Roosevelt/libssh2-1.2.5/src/libssh2_config.h -o lolbaise /home/Roosevelt/libssh2-1.2.5/example/scp.c /home/Roosevelt/libssh2-1.2.5/example/scp.c:7:28: error: libssh2_config.h: No such file or directory /home/Roosevelt/libssh2-1.2.5/example/scp.c: In function 'main': /home/Roosevelt/libssh2-1.2.5/example/scp.c:39: error: storage size of 'sin' isn't known /home/Roosevelt/libssh2-1.2.5/example/scp.c:81: error: 'AF_INET' undeclared (first use in this function) /home/Roosevelt/libssh2-1.2.5/example/scp.c:81: error: (Each undeclared identifier is reported only once /home/Roosevelt/libssh2-1.2.5/example/scp.c:81: error: for each function it appears in.) /home/Roosevelt/libssh2-1.2.5/example/scp.c:81: error: 'SOCK_STREAM' undeclared (first use in this function) /home/Roosevelt/libssh2-1.2.5/example/scp.c:87: error: invalid application of 'sizeof' to incomplete type 'struct sockaddr_in' Here is the new errors: scp.c:(.text+0x106): undefined reference to `libssh2_init' scp.c:(.text+0x1fe): undefined reference to `libssh2_session_init_ex' scp.c:(.text+0x234): undefined reference to `libssh2_session_startup' scp.c:(.text+0x288): undefined reference to `libssh2_hostkey_hash' scp.c:(.text+0x36f): undefined reference to `libssh2_userauth_password_ex' scp.c:(.text+0x3e7): undefined reference to `libssh2_userauth_publickey_fromfile_ex' scp.c:(.text+0x437): undefined reference to `libssh2_scp_recv' scp.c:(.text+0x531): undefined reference to `libssh2_channel_read_ex' scp.c:(.text+0x5f8): undefined reference to `libssh2_channel_free' scp.c:(.text+0x628): undefined reference to `libssh2_session_disconnect_ex' scp.c:(.text+0x636): undefined reference to `libssh2_session_free' scp.c:(.text+0x66e): undefined reference to `libssh2_exit' collect2: ld returned 1 exit status
I just cloned the current git build and went into the 1.2.5 relase but I'm unable to reproduce your problem. ./buildconf ./configure make works fine. What are you trying to do exactly?
3,014,011
3,014,164
C++: Weird Segmentation fault
I am trying to print something using C++. However, I am running into a strange bug that has left me clueless, I use the following code: PRINTDLG pd; ZeroMemory(&pd, sizeof(pd)); pd.lStructSize = sizeof(pd); pd.Flags = PD_RETURNDEFAULT; PrintDlg(&pd); // Set landscape DEVMODE* pDevMode = (DEVMODE*)GlobalLock(pd.hDevMode); pDevMode->dmOrientation = DMORIENT_LANDSCAPE; pd.hwndOwner = mainWindow; pd.Flags = PD_RETURNDC | PD_NOSELECTION; GlobalUnlock(pd.hDevMode); if (PrintDlg(&pd)) { DOCINFO di; di.cbSize = sizeof(DOCINFO); di.lpszDocName = "Test Print"; di.lpszOutput = (LPTSTR)NULL; di.fwType = 0; //start printing StartDoc(pd.hDC, &di); int a; int b; int c; int d; int e; int f; // int g; // Uncomment this -> CRASH EndDoc(pd.hDC); DeleteDC(pd.hDC); } else { cout << "Did not print: " << CommDlgExtendedError() << endl; } The moment I uncomment 'int g;' I get a: "Program received signal SIGSEGV, Segmentation fault." I use codeblocks and the mingw compiler, both up to date. What could be causing this?
I don't know if this is a potential problem here - but you should always initialize all members of structures (like you did with the PRINTDLG). In the DOCINFO struct the lpszDataType member is uninitialized. Instead of using ZeroMemory or memset, I prefer something like DOCINFO di = {0};
3,014,298
3,014,457
MFC , C++ in embedded(semiconductor) projects
What are the internal features/aspects of C++/ VC++ and MFC that are used for embedded(semiconductor) projects by large IT companies. I ask this becuase I need to be prepared for one such poistion. please reply.
MFC isn't used in typical embedded projects. It's an old Microsoft library, typically used for PC software as opposed to embedded software. C++ (the language) and VC++ (a Microsoft compiler for the C++ language) are used in embedded projects. However, the Microsoft compiler cannot target common embedded platforms such as ARM-linux. You'd find that GCC is more commonly used as the C++ compiler for embedded ARM-linux platforms.
3,014,832
3,014,878
consts and other animals
Possible Duplicate: what is the difference between const int*, const int * const, int const * i have a cpp code wich i'm having trouble reading. a class B is defined now, i understand the first two lines, but the rest isn't clear enough. is the line "B const * pa2 = pa1" defines a const variable of type class B? if so, what does the next line do? B a2(2); B *pa1 = new B(a2); B const * pa2 = pa1; B const * const pa3 = pa2; also, i'm having trouble figuring out the difference between these two: char const *cst = “abc”; const int ci = 15; thank you
This code declares a pointer to a constant B - in other words, it cannot be used to change the value of what it is pointing to: B const * pa2 = pa1; Alternatively, the following code declares a constant pointer to a constant B - so, pa3 cannot be used to change the value of what it is pointing to, and it cannot be modified to point to something else: B const * const pa3 = pa2; This page contains an explanation of const pointers. To address your second question, char const *cst = “abc”; - Declares a pointer to a constant char - in this case it is the string "abc". const int ci = 15; - Declares a constant integer 15, which cannot be changed.
3,014,879
3,015,500
QT - How to apply a QToolTip on a QLineEdit
On a dialog I have a QLineEdit and a button. I want to enable a tool tip for the QLineEdit(in it or under it) when I press the button. Please give me a code snippet.
Here is a simple example: class MyWidget : public QWidget { Q_OBJECT public: MyWidget(QWidget* parent = 0) : QWidget(parent) { QVBoxLayout* layout = new QVBoxLayout(this); edit = new QLineEdit(this); layout->addWidget(edit); showButton = new QPushButton("Show tool tip", this); layout->addWidget(showButton); hideButton = new QPushButton("Hide tool tip", this); layout->addWidget(hideButton); connect(showButton, SIGNAL(clicked(bool)), this, SLOT(showToolTip())); connect(hideButton, SIGNAL(clicked(bool)), this, SLOT(hideToolTip())); } public slots: void showToolTip() { QToolTip::showText(edit->mapToGlobal(QPoint()), "A tool tip"); } void hideToolTip() { QToolTip::hideText(); } private: QLineEdit* edit; QPushButton* showButton; QPushButton* hideButton; }; As you can see, there is no easy way to just enable the tool tip of some widget. You have to provide global coordinates to QToolTip::showText. Another way to do this is to create a QHelpEvent yourself and post this event using QCoreApplication::postEvent. This way, you can specify the text to be shown in your widget using QWidget::setToolTip. You still have to provide global coordinates, though. I am really interested in why you want to do this since tool tips are intended to be shown only when you hover your mouse or when you ask for the "What's this" information. It looks like bad design to use it for something else. If you want to give a message to the user, why don't you use QMessageBox?
3,014,947
3,015,033
how-to add "warnings as error" rule to Qt .pro file?
When I usually work on a C++ project, one of the first things I do is setting up the "treat warning as errors" on my compiler. When using Qt, qmake generates the Makefile for you and doesn't include this option on the compilation commands. I'm pretty sure there is a way to add such an option (and others) into the generated Makefile but I couldn't figure it out. How would I do that ? I'm using the open-source version of Qt with g++ as the compiler.
You can use QMAKE_CXXFLAGS in pro file to specify compiler flags: QMAKE_CXXFLAGS += -Werror
3,015,263
3,020,675
Segfaults with singletons
// Non singleton class MyLogManager { void write(message) {Ogre::LogManager::getSingletonPtr()->logMessage(message);} } class Utils : public singleton<Utils> { MyLogManager *handle; MyLogManager& getHandle { return *handle; } }; namespace someNamespace { MyLogManager &Log() { return Utils::get_mutable_instance().getHandle(); } } int main() { someNamespace::Log().write("Starting game initializating..."); } In this code I'm using boost's singleton (from serialization) and calling Ogre's log manager (it's singleton-type too). The program fails at any trying to do something with Ogre::LogManager::getSingletonPtr() object with code User program stopped by signal (SIGSEGV) I checked that getSingletonPtr() returns address 0x000 But using code Utils::get_mutable_instance().getHandle().write("foo") works good in another part of program. What's wrong could be there with calling singletons? Real version of Utils class: class Utils : public singleton<Utils> { protected: ConfigManager *configHandlePtr; LogManager *logHandlePtr; public: Utils() { configHandlePtr = new ConfigManager(); string engineLog = configHandle().getValue<string>("engine.logFilename", "Engine.log"); logHandlePtr = new LogManager(engineLog); } ~Utils() { delete configHandlePtr; delete logHandlePtr; } ConfigManager &configHandle() const { return *configHandlePtr; } LogManager &logHandle() const { return *logHandlePtr; } }; And here is the real code of LogManager class: class LogManager { protected: string mDefaultPath; public: LogManager(const string &logPath = "Engine.log") : mDefaultPath(logPath) { } void write(const string &message, const string logFile = "") { string workPath = mDefaultPath; Ogre::LogManager *logHandle = Ogre::LogManager::getSingletonPtr(); // [logHandle=0x000] Ogre::Log *log2Handle = logHandle->getLog(workPath); // [SEGFAULT] log2Handle->logMessage(message); Ogre::LogManager::getSingletonPtr()->logMessage(message); } }; UPDATE: I have a static library (there is my engine code) and the main own programm which links static this library. When I call my config handle (which doesn't use Ogre) everything is okay! There is also resourceManager, it uses Ogre too. And it fails like logManager. Both this managers uses Ogre's singleton. Maybe it's impossible to call it from another library?
It feels like you have typical "static initialization order fiasco" - your Utils instance created before one (or both) of other singletons. Try change Utils::configHandle() to something like this: ConfigManager &configHandle() const { static std::auto_ptr<ConfigManager> configHandlePtr(0); if (!configHandlePtr.get()) { configHandlePtr.reset(new ConfigManager()); // init configHandlePtr like you want } return *configHandlePtr; }
3,015,306
3,015,403
What exactly does -march=native do?
Gentoo Wiki told me the following: Warning: GCC 4.2 and above support -march=native. -march=native applies additional settings beyond -march, specific to your CPU. Unless you have a specific reason not to (e.g. distcc cross-compiling), you should probably be using -march=native, rather than anything listed below. What are those additional settings?
Nevermind. $ cc -march=core2 -E -v - </dev/null 2>&1 | grep cc1 /[...]/cc1 -E -quiet -v -iprefix /[...]/4.3.2/ - -march=core2 $ cc -march=native -E -v - </dev/null 2>&1 | grep cc1 /[...]/cc1 -E -quiet -v -iprefix /[...]/4.3.2/ - -march=core2 -mcx16 -msahf --param l1-cache-size=32 --param l1-cache-line-size=64 -mtune=core2 I'm starting to like this option a lot. -mcx16 and -msahf are two additional CPU instructions gcc can now use, which weren't available in earlier Core2's.
3,015,311
3,015,616
Why this Explicit P/Invoke does not work?
The following .net to native C code does not work, any ideas extern "C" { TRADITIONALDLL_API int TestStrRef( __inout char* c) { int rc = strlen(c); std::cout << "the input to TestStrRef is: >>" << c << "<<" ; c = "This is from the C code "; return rc; } } [DllImport("MyDll.dll", SetLastError = true)] static extern int TestStrRef([MarshalAs(UnmanagedType.LPStr)] ref string s); String abc = "InOut string"; TestStrRef(ref abc); At this point Console.WriteLine(abc) should print "This is from the C code " but doesn't, Any ideas on what's wrong ? FYI - i have another test function not using ref type string, it works just fine
Your code wrong at C side also. __inout annotation just tell compiler you can change buffer to which "c" argument pointed. But pointer itself located in stack and does not return to caller if you modified "c" argument. Your declaration may look like: extern "C" { TRADITIONALDLL_API int TestStrRef( __inout char** c) { int rc = strlen(*c); std::cout << "the input to TestStrRef is: >>" << *c << "<<" ; *c = "This is from the C code "; return rc; } } And C# side: [DllImport("MyDll.dll", SetLastError = true)] static extern int TestStrRef(ref IntPtr c); { String abc = "InOut string"; IntPtr ptrOrig = Marshal.StringToHGlobalAnsi(abc) IntPtr ptr = ptrOrig; // Because IntPtr is structure, ptr contains copy of ptrOrig int len = TestStrRef(ref ptr); Marshal.FreeHGlobal(ptrOrig); // You need to free memory located to abc' native copy string newAbc = Marshal.PtrToStringAnsi(ptr); // You cannot free memory pointed by ptr, because it pointed to literal string located in dll code. }
3,015,444
3,015,774
Instant crashing after replacing calls to clock() with MPI_Wtime()
I have an MPI program that I'm developing on a local computer, but need to run on a remote machine. I used clock() to measure time, but after discovering that it doesn't work well enough on the remote machine (due to a completely different architecture), I replaced a few calls to clock() with MPI_Wtime(), which yielded the required results. The program still runs on both the local and remote machines. However, I just went and replaced all the other calls to clock() with MPI_Wtime(), and now launching the program on the local machine immediately causes the processes to stop with exit code -1073741819. Even if I put a cout in the very first line of main(), there's no output, so I'm fairly sure it's not a programming fault on my part, but I have no idea what's wrong. How can changes in the source code cause a program to fail before the changed code (or any code, for that matter) is executed?
Are you calling MPI_Wtime() from the constructor of a static object? These run before main().
3,015,507
3,015,678
C++ template member specialization - is this a compiler limitation?
Is it possible to do this kind of specialization? If so, how? The specialization in question is marked //THIS SPECIALIZATION WILL NOT COMPILE I have used VS2008, VS2010, gcc 4.4.3 and neither can compile this. I know i can avoid this by overloading func but i want to know if there is a way to do this with template specialization. (impractical/inadvisable though it may be) #include<iostream> #include<string> using namespace std; template <typename ALPHA> class klass{ public: template <typename BETA> void func(BETA B); }; template <typename ALPHA> template <typename BETA> void klass<ALPHA>::func(BETA B){ cout << "I AM A BETA FUNC: " << B <<endl; } //THIS SPECIALIZATION WILL NOT COMPILE template <typename ALPHA> template <> void klass<ALPHA>::func(string B){ cout << "I AM A SPECIAL BETA FUNC: " << B <<endl; } int main(){ klass<string> k; k.func(1); k.func("hello"); return 0; }
To answer the question you ask in the title: no, this is not a compiler limitation. This is a language limitation. In C++, in order to explicitly specialize a nested template (be that a class template or a member function template) you have to also explicitly specialize the enclosing template. You are trying to explicitly specialize the nested template without specializing the enclosing template. This will not compile. When it comes to member function templates, when template parameter is associated with some function parameter (as in your case), you can often replace explicit specialization with overloading, as suggested in Tyler's answer. In other situations you'd have to use a different workaround.
3,015,582
3,015,871
Direct boost serialization to char array
Boost serialization doc's assert that the way to serialize/deserialize items is using a binary/text archive with a stream on the underlying structure. This works fine if I wan't to use the serialized data as an std::string, but my intention is to convert it directly to a char* buffer. How can I achieve this without creating a temporary string? Solved! For the ones that wanted a example: char buffer[4096]; boost::iostreams::basic_array_sink<char> sr(buffer, buffer_size); boost::iostreams::stream< boost::iostreams::basic_array_sink<char> > source(sr); boost::archive::binary_oarchive oa(source); oa << serializable_object;
IIUC, you would like to write to a preallocated array of fixed size. You could use a boost::iostreams::array_sink (wrapped with stream to give it an std::ostream interface) for that.
3,015,624
41,755,724
how to declare type conversion in header file and implement in cpp file?
it doesn't work for me. i have a header file and a cpp file. need to define a conversion operator from my class to INT, but it gives me "syntax error" when declaring it in the H file and implementing in the cpp file. maybe i got the syntax wrong? in the H file i have in "public": operator int(); and in the cpp file i have: A::operator int() { return mNumber ;} if i implement the function in the H file it works, but i don't want to do that. can anyone help?
I also wanted to separate the class declaration from the implementation. The critical missing ingredient was the const: // Foobar.hpp class Foobar { public: Foobar() : _v(42) {} operator int() const; private: int _v; }; And then in the implementation file: #include "Foobar.hpp" Foobar::operator int() const { return _v; } See this reference
3,015,632
3,016,071
how to use cpp source for 2 projects
I'm not sure if I am going about this the right way. I am making some c++ classes to use in 2 apps. I am going to have to compile them to be used in a Cocoa app and later be compiled for use with fastcgi. Should I create a dynamic library?
Don't forget that you have static library as an option too. On some platforms dynamic libs come with a bunch of annoying baggage. They're also slightly slower (though this is usually beside the point). They also can't be replaced without recompiling the program (you might be more concerned about this in a web environment). Finally, when you're only running one of the programs on a computer you gain nothing by making the lib dynamic...and little when there's only two.
3,015,964
3,015,990
Using template parameters as template parameters
Why is the following code invalid? template <typename S, typename T> struct B{ void f(T t, S s) {t.f<S>(s); } }; gcc 4.3.4 complains that it "expected primary-expression before '>' token", i.e. that "S" wasn't a valid primary-expression.
You need to specify that f is a template: void f(T t, S s) { t.template f<S>(s); } C++ doesn’t know this (at this point) since f’s type depends on the type of the template parameter T. Furthermore, the following syntax would be ambiguous: does < mean the start of a template list or a less-than operator? To help C++ figure that out you need to specify that f is a template, otherwise C++ cannot parse the following part because the parse itself depends on the type of T.
3,016,350
3,019,274
Qt: Animating the 'roll down' of a QWidget
I have a QWidget that contains various other widgets. I want to animate it appearing on the screen by gradually revealing it from the top down, increasing it's height from 0 to whatever it's natural height would be. The way I have it currently is: mAnimation = new QPropertyAnimation(this, "maximumHeight"); mAnimation->setStartValue(0); mAnimation->setEndValue(400); mAnimation->start(); This has two issues: - It crashes when the height reaches a certain height, with a "qDrawShadeRect: Invalid parameters" error. - If I change the 0 to 100, it works fine, but the widgets contained within the QWidget I'm animating have their layout changed as the widget animates, starting very squashed together and gradually spreading apart as they get more space. This looks ugly! Does anyone have any suggestions?
For the crash, I'd recommend grabbing a stack trace and, assuming the problem isn't in your code, report it as a bug. For the second, rather than render the widget exactly where you want it with different sizes, render it as you'd like it to be seen. For example: Use a QStackWidget with two items: the actual widget and the desired widget The desired widget is really just a QWidget::render() to a pixmap of what you want the widget to look like. For the animation, show the pre-rendered widget and then switch once you've reached the target size.
3,016,399
3,021,382
Qt - How to post a banner on the dialog?
I have a directroy where I have several pictures and gif animations. I want to post that pictures and animations on a QDialog in an infinite loop (by cyclically changing pictures in 2 minutes interval) and on that pictures and animations I want to set a link so that when you click the browser open the set link. How I could do this? Please consider that I know how to get all .jpg amd .gif file names (full path) in the directory. Consider there is a QStringList fileNameList; which contains that full paths.
You can use 2 QLabels for this. The first one will be used for static images like jpg and the second one for animations. In the first one you can use setPixmap to set the image and in the second one you need to create a QMovie object giving it the gif file in the constructor. Once the object is created you can assign the movie to a label using the setMovie() function. The movie doesn't start until you call start() in the QMovie object. With this you have animations and static images. Since you want then change every 2 seconds I would suggest to store all the file names in a QList and then use a QTimer to read the next file name and load it in one of the labels (the one for static images or the other) and hide the one that is not going to be visible. To open links you can subclass the QLabel class and override the mousePressEvent method. Inside the method you can call QDesktopServices::openExternalLink(link). You can add the link as a member of your subclass. Good luck!
3,016,524
3,016,589
Use of function pointers for callling functions in a DLL
Is it possible to call a function in a DLL loaded dynamically without making use of function pointers.
Yes, sort of, depending on what you're trying to accomplish. At least for some purposes, the linker's delayload switch can give roughly the effect of explicit dynamic linking, without requiring that you define pointers to all the functions you're going to use, use GetProcAddress to assign values to those pointers, etc.
3,016,683
3,017,368
The difference between traditional DLL and COM DLL
I am currently studying COM. I found that COM DLL is kind of built upon the traditional DLL infrastructure. When we build COM DLLs, we still rely on the traditional DLL export methods to lead us to the internal COM co-classes. If COM is for component reusing at the binary level, I think the traditional DLL can achieve the same thing. They both expose functions, they are both binary, so what's the point of turning to COM approach? Currently, I have the feeling that the traditional DLL expose methods in a "flat" manner, while the COM DLL expose methods in an "OOP" hierarchy manner. And the OOP manner seems to be a better approach. Could this be the reason why COM prevails? Many thanks.
No, there's a Big difference. COM has a well defined protocols for creating objects, exposing methods, managing memory, publishing type information, managing threading. There is practically no language left that doesn't support using a COM server, no matter what language it was written in. You will not get that from exposing your own functions directly. That will likely be only usable from a program written in C/C++ (so it can read your header files), compiled with the exact same version of the C++ compiler and no lack of all kinds of interop problems. Something as simple as exposing a C++ class object like std::string is not safe. Neither the memory layout is guaranteed to be compatible, nor is there any kind of memory ownership protocol. It could well be more OOPy, COM doesn't support inheritance because OOP is so hard to get compatible at the binary level. That problem requires runtime support that all code buys into, VMs like .NET and Java.
3,016,714
3,016,764
How does one hide a win32 app window?
I want to run the app in silent mode by passing in a parameter, otherwise I will show the window.
ShowWindow(... SW_HIDE ...) doesn't work? The best practice here is to not create the window in the first place. Nothing forces you to actually create a window in InitInstance. Though if you're working with MFC it's likely a lot of your application/domain/business logic is sitting there, tightly coupled to those MFC message handlers and so forth. In which case the window will need to exist.
3,016,749
3,016,760
Do static local variables in a class persist between objects?
class MyClass { static int staticInt; void instanceMethod( int param ) { static int parameter = param; } } Clearly staticInt is shared between all instance of MyClass. But can different instances of MyClass have different values of parameter the static local variable within instaceMethod? Update What about between program executions? Certainly they could be different in multiple program instances? What defines "scope" there - the execution unit? The c++ runtime? Update Thanks - this helped me squash a critical bug. Wish I could accept them all, but I'm going with the first answer with no other criteria.
There is exactly one instance of parameter. If you want an instance of parameter for each instance of the class, use a nonstatic member variable.
3,016,772
3,016,845
Dynamic memory allocation with default values
class A { private: int m_nValue; public: A() { m_nValue = 0; } A(int nValue) { m_nValue = nValue); ~A() {} } Now in main if i call A a(2);// 2 will be assigned for m_nValue of object A. Now how do we do this if i want to define an array of objects. Also how do we do this if i dynamically create objects using operator new like A *pA; pA = new A[5];// while creating the object i want the parameterised constructor to be //called I hope the question is clear. Do let me know if more explanation is needed
You cannot do this. If you want to dynamically allocate an array, it has to be a default-constructable object. This means, it needs to have a constructor with no parameters, which is the one that will be used.
3,016,839
3,016,922
How can I call a function from a dll?
How could I call a function from a DLL? I tried to declare a void pointer and to store in it the result of GetProcAddress... but didn't work. I also wanted to declare an unsigned long int (I saw it somewhere on the internet), but then I didn't know how to continue on. :D So, would anybody mind giving me a hand?
Try for something like this. typedef int (*PFuncMethods)( int args ); hDLL = LoadLibrary(L"your.dll"); if( !m_hDLL ) return; methods = (PFuncMethods)GetProcAddress(hDLL,"methods"); if ( !(methods) ) { FreeLibrary(hDLL); hDLL = NULL; methods = NULL; return; } if( methods(1) == 0) ... the method name is where you might be stuck aswell. C++ has name mangling for overloading (even if it's not overloaded) and that depends on the compiler. You can either work out the mangled name or turn off mangling for the function by using extern "C". You might use a tool like depends.exe to see all the functions with exact name you would have to use. It is much easier to statically link to the DLL using the (import)lib file in windows.
3,016,899
3,016,982
Qt QMainWindow at Close
this may seem like a very simple question, but I want to dump some data whenever the QMainWindow closes, so I used the following piece of code: QObject::connect(MainWindow.centralwidget, SIGNAL(destroyed()), this, SLOT(close())); But this doesn't seem to make it call close(). Am I doing this wrong?. Isn't the centralwidget suppose to be destroyed?. Or perhaps the application closes before close() can be called?. Any other ways of doing it then?
I'd try QGuiApplication::lastWindowClosed() instead.
3,016,956
3,016,986
How do I install the OpenSSL libraries on Ubuntu?
I'm trying to build some code on Ubuntu 10.04 LTS that uses OpenSSL 1.0.0. When I run make, it invokes g++ with the "-lssl" option. The source includes: #include <openssl/bio.h> #include <openssl/buffer.h> #include <openssl/des.h> #include <openssl/evp.h> #include <openssl/pem.h> #include <openssl/rsa.h> I ran: $ sudo apt-get install openssl Reading package lists... Done Building dependency tree Reading state information... Done openssl is already the newest version. 0 upgraded, 0 newly installed, 0 to remove and 3 not upgraded. But I guess the openssl package doesn't include the library. I get these errors on make: foo.cpp:21:25: error: openssl/bio.h: No such file or directory foo.cpp:22:28: error: openssl/buffer.h: No such file or directory foo.cpp:23:25: error: openssl/des.h: No such file or directory foo.cpp:24:25: error: openssl/evp.h: No such file or directory foo.cpp:25:25: error: openssl/pem.h: No such file or directory foo.cpp:26:25: error: openssl/rsa.h: No such file or directory How do I install the OpenSSL C++ library on Ubuntu 10.04 LTS? I did a man g++ and (under "Options for Linking") for the -l option it states: " The linker searches a standard list of directories for the library..." and "The directories searched include several standard system directories..." What are those standard system directories?
You want to install the development package, which is libssl-dev: sudo apt-get install libssl-dev
3,017,039
3,017,075
How to pass a function in a function?
That's an odd title. I would greatly appreciate it if somebody could clarify what exactly I'm asking because I'm not so sure myself. I'm watching the Stanford videos on Programming Paradigms(that teacher is awesome) and I'm up to video five when he started doing this: void *lSearch( void* key, void* base, int elemSize, int n, int (*cmpFn)(void*, void*)) Naturally, I thought to myself, "Oi, I didn't know you could declare a function and define it later!". So I created my own C++ test version. int foo(int (*bar)(void*, void*)); int bar(void* a, void* b); int main(int argc, char** argv) { int *func = 0; foo(bar); cin.get(); return 0; } int foo(int (*bar)(void*, void*)) { int c(10), d(15); int *a = &c; int *b = &d; bar(a, b); return 0; } int bar(void* a, void* b) { cout << "Why hello there." << endl; return 0; } The question about the code is this: it fails if I declare function int *bar as a parameter of foo, but not int (*bar). Why!? Also, the video confuses me in the fact that his lSearch definition void* lSearch( /*params*/ , int (*cmpFn)(void*, void*)) is calling cmpFn in the definition, but when calling the lSearch function lSearch( /*params*/, intCmp ); also calls the defined function int intCmp(void* elem1, void* elem2); and I don't get how that works. Why, in lSearch, is the function called cmpFn, but defined as intCmp, which is of type int, not int* and still works? And why does the function in lSearch not have to have defined parameters?
int (*cmpFn)(void*, void*) is a function pointer -- a pointer to a function that can be called later. When you call iSearch you pass it a function that takes two void* and returns an int, and it binds that to the parameter cmpFn. Then iSearch can do something like int x = cmpFn(voidPtr1, voidPtr2); to call that function, passing it voidPtr1 and voidPtr2 as its arguments and storing the return value in x You can try a simple example by just declaring a function pointer and using it in the same function: int test1(int x) {return x;} int test2(int x) {return x+1;} int main(int argc, char** argv) { int (*fn)(int); // Function pointer named 'fn' that can hold a function that takes one int argument and returns an int int rtn; fn = test1; // Assign the 'test1' function to 'fn' rtn = fn(4); // Call 'fn' ('test1') with the argument 4; it returns 4 and stores it in 'rtn' fn = test2; // Assign the 'test2' function to 'fn' rtn = fn(4); // Call 'fn' ('test2') with the argument 4; it returns 5 and stores it in 'rtn' } It fails if you declare int *bar because that's not a function pointer, it's just a pointer to an integer. The syntax for function pointers is rtn_type (*name)(param1_type, param2_type, ...)
3,017,051
3,017,518
Obtain container type from (its) iterator type in C++ (STL)
It is easy given a container to get the associated iterators, example: std::vector<double>::iterator i; //An iterator to a std::vector<double> I was wondering if it is possible, given an iterator type, to deduce the type of the "corresponding container" (here I am assuming that for each container there is one and only one (non-const) iterator). More precisely, I would like a template metafunction that works with all STL containers (without having to specialize it manually for each single container) such that, for example: ContainerOf< std::vector<double>::iterator >::type evaluates to std::vector<double> Is it possible? If not, why? Thank you in advance for any help!
I don't think this would be possible. On some STL libraries you actually have a vector iterator as a pointer type, i.e. std::vector<T>::iterator is a T* so I can't think of any way you could get back to the container type from that.
3,017,095
3,017,130
Interaction between for loops with clock function?
Can someone explain me the exact interaction in context of delay between the two for loops with clock function. How does for1 interact with for2 on the cout statement(30 on 640000000)? start=clock(); cout<<endl<<start<<endl; for(delay=0; delay<30; delay++) for(i=0; i<640000000; i++); end=clock(); cout<<end<<endl; cout<<"Num of ticks for non reg-loop: "; cout<<end-start<<'\n';
Probably a decent optimizer will see that the loop is a no-op and optimize it out completely, so there will be almost no difference between start and end. If it's not optimized out, the two loops are simply working around the fact that 30*640000000 is bigger than could be stored in a 32-bit integer. It runs the inner 640000000 loop 30 times to attempt to magnify the delay. EDIT: So for each of 30 times (using variable delay), it creates another loop (using variable i) starting at 0. It then increments i 640000000 times, each increment taking a small fraction of time (if not optimized away). Then the inner loop completes, delay is increased by 1, and the inner loop starts over at 0 again. EDIT2: If you're just trying to add a delay, have you considered using sleep or usleep or the corresponding Windows function(s) rather than trying to implement a sleep by iteration?
3,017,162
3,017,438
How to get total cpu usage in Linux using C++
I am trying to get total cpu usage in %. First I should start by saying that "top" will simply not do, as there is a delay between cpu dumps, it requires 2 dumps and several seconds, which hangs my program (I do not want to give it its own thread) next thing what I tried is "ps" which is instant but always gives very high number in total (20+) and when I actually got my cpu to do something it stayed at about 20... Is there any other way that I could get total cpu usage? It does not matter if it is over one second or longer periods of time... Longer periods would be more useful, though.
cat /proc/stat http://www.linuxhowtos.org/System/procstat.htm I agree with this answer above. The cpu line in this file gives the total number of "jiffies" your system has spent doing different types of processing. What you need to do is take 2 readings of this file, seperated by whatever interval of time you require. The numbers are increasing values (subject to integer rollover) so to get the %cpu you need to calculate how many jiffies have elapsed over your interval, versus how many jiffies were spend doing work. e.g. Suppose at 14:00:00 you have cpu 4698 591 262 8953 916 449 531 total_jiffies_1 = (sum of all values) = 16400 work_jiffies_1 = (sum of user,nice,system = the first 3 values) = 5551 and at 14:00:05 you have cpu 4739 591 289 9961 936 449 541 total_jiffies_2 = 17506 work_jiffies_2 = 5619 So the %cpu usage over this period is: work_over_period = work_jiffies_2 - work_jiffies_1 = 68 total_over_period = total_jiffies_2 - total_jiffies_1 = 1106 %cpu = work_over_period / total_over_period * 100 = 6.1% Hope that helps a bit.
3,017,234
3,017,262
How to handle asynchronous socket receiving in C++?
I'm currently using a thread to handle Connect and Send calls asynchronously. This is all working fine, but now I want to make receiving asynchronous too. How should I receive data without pausing the whole queue while waiting for data? The only solution I can think of right now is a second thread.
Look into non-blocking sockets and polling APIs like select(2)/poll(2)/epoll(4)/kqueue(2). Specifically in C++, look into boost::asio.
3,017,264
3,017,290
Is it good practice to make getters and setters inline?
public: inline int GetValue() const { return m_nValue; } inline void SetValue(int nNewValue) { this -> m_nValue = nNewValue; } On Learn C++, they said it would run faster. So, I thought it would be great to use on getters and setters. But maybe, there are some drawbacks to it?
I don't inline anything until a profiler has specifically told me that not inlining is resulting in a performance problem. The C++ compiler is very smart and will almost certainly automatically inline such simple function like this for you. And typically it's smarter than you are and will do a much better job at determining what should or should not be inlined. I would avoid thinking about what to or not to inline and focus on the solution. Adding the inline keyword later (which is not a guarantee of inline BTW) is very easy to do and potential places can be found readily with a profiler.
3,017,389
3,017,431
Question about my sorting algorithm in C++
i have following code in c++ #include <iostream> using namespace std; void qsort5(int a[],int n){ int i; int j; if (n<=1) return; for (i=1;i<n;i++) j=0; if (a[i]<a[0]) swap(++j,i,a); swap(0,j,a); qsort5(a,j); qsort(a+j+1,n-j-1); } int main() { return 0; } void swap(int i,int j,int a[]) { int t=a[i]; a[i]=a[j]; a[j]=t; } i have problem 1>c:\users\dato\documents\visual studio 2008\projects\qsort5\qsort5\qsort5.cpp(13) : error C2780: 'void std::swap(std::basic_string<_Elem,_Traits,_Alloc> &,std::basic_string<_Elem,_Traits,_Alloc> &)' : expects 2 arguments - 3 provided 1> c:\program files\microsoft visual studio 9.0\vc\include\xstring(2203) : see declaration of 'std::swap' 1>c:\users\dato\documents\visual studio 2008\projects\qsort5\qsort5\qsort5.cpp(13) : error C2780: 'void std::swap(std::pair<_Ty1,_Ty2> &,std::pair<_Ty1,_Ty2> &)' : expects 2 arguments - 3 provided 1> c:\program files\microsoft visual studio 9.0\vc\include\utility(76) : see declaration of 'std::swap' 1>c:\users\dato\documents\visual studio 2008\projects\qsort5\qsort5\qsort5.cpp(13) : error C2780: 'void std::swap(_Ty &,_Ty &)' : expects 2 arguments - 3 provided 1> c:\program files\microsoft visual studio 9.0\vc\include\utility(16) : see declaration of 'std::swap' 1>c:\users\dato\documents\visual studio 2008\projects\qsort5\qsort5\qsort5.cpp(14) : error C2780: 'void std::swap(std::basic_string<_Elem,_Traits,_Alloc> &,std::basic_string<_Elem,_Traits,_Alloc> &)' : expects 2 arguments - 3 provided 1> c:\program files\microsoft visual studio 9.0\vc\include\xstring(2203) : see declaration of 'std::swap' 1>c:\users\dato\documents\visual studio 2008\projects\qsort5\qsort5\qsort5.cpp(14) : error C2780: 'void std::swap(std::pair<_Ty1,_Ty2> &,std::pair<_Ty1,_Ty2> &)' : expects 2 arguments - 3 provided 1> c:\program files\microsoft visual studio 9.0\vc\include\utility(76) : see declaration of 'std::swap' 1>c:\users\dato\documents\visual studio 2008\projects\qsort5\qsort5\qsort5.cpp(14) : error C2780: 'void std::swap(_Ty &,_Ty &)' : expects 2 arguments - 3 provided 1> c:\program files\microsoft visual studio 9.0\vc\include\utility(16) : see declaration of 'std::swap' 1>c:\users\dato\documents\visual studio 2008\projects\qsort5\qsort5\qsort5.cpp(16) : error C2661: 'qsort' : no overloaded function takes 2 arguments 1>Build log was saved at "file://c:\Users\dato\Documents\Visual Studio 2008\Projects\qsort5\qsort5\Debug\BuildLog.htm" please help
swap is a function in std which must be included by <iostream>. When you attempt to make calls to your swap, it can't find it (I'll explain in a moment) and instead looks at the std::sort, which takes two arguments (hence the first error). The reason it can't find your swap is because it is declared after it is called. You need to either move the definition of your swap above that of qsort5 or forward declare it: void swap(int i,int j,int a[]); void qsort5(int a[],int n){ ... That tells the compiler that your swap function exists and it will use that when you call swap with 3 arguments.
3,017,411
3,017,508
Why does this class declaration not work on Visual Studio
So I'm trying to get some code that is written for gcc to compile on Visual Studio 2008. I have a problem that I have narrowed down to this: class value_t { public: typedef std::deque<value_t> sequence_t; typedef sequence_t::iterator iterator; }; This code fails: 1>cpptest.cpp 1>c:\program files\microsoft visual studio 9.0\vc\include\deque(518) : error C2027: use of undefined type 'value_t' 1> c:\temp\cpptest\cpptest.cpp(10) : see declaration of 'value_t' 1> c:\temp\cpptest\cpptest.cpp(13) : see reference to class template instantiation 'std::deque<_Ty>' being compiled 1> with 1> [ 1> _Ty=value_t 1> ] 1>c:\program files\microsoft visual studio 9.0\vc\include\deque(518) : error C2027: use of undefined type 'value_t' 1> c:\temp\cpptest\cpptest.cpp(10) : see declaration of 'value_t' However when I try this with std::vector, it compiles fine: class value_t { public: typedef std::vector<value_t> sequence_t; typedef sequence_t::iterator iterator; }; What's wrong? I have tried adding 'typename' everywhere I can think of, but at this point in time I'm thinking it's just a bug in the Dinkumware STL. Can anyone explain what's happening, and/or offer a solution? Thanks.
Its undefined behavior. See this link on c.l.c++.moderated Snip from Daniel K's answer :- the C++ standard (both C++03 and C++0x) says that what you are trying causes undefined behaviour, see [lib.res.on.functions]/2: "In particular, the effects are undefined in the following cases: [..] — if an incomplete type (3.9) is used as a template argument when instantiating a template component."
3,017,425
3,018,880
opencv conversion from a Mat element to IplImage *
How can I convert a Mat element to IplImage * element? Please Help!
Mat mat_img; //.... IplImage ipl_img = mat_img; This puts a header of IplImage on top of mat_img so there is no copying. You can pass &ipl_img to function which need IplImage*.
3,017,462
6,330,990
how can i use youtube chromeless player in desktop application?
i like to use youtube chromeless player in my QT c++ application im using qwebkit , but in the youtube doc's its says: " To test any of these calls, you must have your file running on a webserver...." how can i overcome this restriction and use chromeless player or some alternative?
What exactly do you want from Youtube Chrome-less player. If it is the outlook and GUI then you can create exactly like this in QT. If it is the playability of the files you can use several open source media file APIs, or even QT Media extensions. Youtube chromeless player is just an swf application that can host a file which it can fetch from web. You can also try by giving the local file name as translated to its local host string e.g: using http://localhost/.... Or using file:///C/files/....
3,017,538
3,017,764
OpenCV image conversion from RGB to HSV
When I run this following code on a sample image(RGB), and then process it to display the converted HSV image, Both appear to be different... Can anyone explain why this happens? OR Can you suggest a solution for this not to happen... because it's the same image after all Mat img_hsv,img_rgb,red_blob,blue_blob; img_rgb = imread("pic.png",1); cvtColor(img_rgb,img_hsv,CV_RGB2HSV); namedWindow("win1", CV_WINDOW_AUTOSIZE); imshow("win1", img_hsv);
I don't know the new (2.x) OpenCV well enough yet, but usually images loaded in OpenCV are in CV_BGR channel order and not RGB, therefore you most likely want CV_BGR2HSV OpenCV does not actually "know" HSV, it will just encode Hue in first channel, Saturation in second and Value in third. If you display an image in OpenCV, highgui assumes it's a BGR image, thus interpreting the first channel (now Hue) as Blue etc.
3,017,642
3,017,664
OpenGL: How to update only a portion of a texture?
I dont want to update the whole texture every time i change a small part of it, what is the command for this? And when i have mipmapping on, set with GL_GENERATE_MIPMAP, how optimized is that internally? will it calculate whole image again, or just the part i updated?
glTexSubImage2D. Mipmap generation process is implementation dependant, it probably will update the whole mipmap chain.
3,017,745
3,017,793
Given Date, Get Day of Week - SYSTEMTIME
Is it possible to determine the day of the week, using SYSTEMTIME, if a date (month-day-year) is provided or is this structure one-way only? What is the most lightweight way to accomplish what I am asking if SYSTEMTIME cannot do it (using Win32)?
According to the msdn, the wDayOfWeek member is ignored when converting SYSTEMTIME to FILETIME. When converting back, it's filled in. SYSTEMTIME t = { 2010, 6, -1 /*ignored*/, 11 }; FILETIME ft; HRESULT hrto = SystemTimeToFileTime( &t, &ft ); HRESULT hrback = FileTimeToSystemTime( &ft, &t ); WORD dayofweek = t.wDayOfWeek;
3,017,814
3,017,854
check compiler version in visual studio 2008
Im writing application in c++ and after try to run built (in debug mode) application on another machine I had error (The application has failed to start because its side-by-side configuration is incorect). I realised that there are missed DLLs from windows\WinSxS\ But I dont really know which folder contains what I really need and secondly I dont know how to check my compiler version in visual studio. Thanks for help
Compile with your runtime library set to multi threaded instead of multi threaded DLL. 1) Right click on your project, click on properties 2) Under Configuration Properties -> C/C++ -> Code Generation 3) Change the Runtime Library value to be Multi Threaded Debug (if in debug) or Multi Threaded Release (if in release) Otherwise you may want to install the Visual Studio 2008 Redistributable Package (x86) You can also check to make sure both computers that have VS are running VS 2008 SP1 update.
3,017,915
3,017,943
Displaying a `std::map`
Declared a map early on: map<char*,char*> rtable; // used to store routing information Now I'm attempting to display the contents of the map: void Routes::viewroutes(){ typedef map<char*, char*>::const_iterator iter; for (iter=rtable.begin(); iter != rtable.end(); ++iter) { cout << iter->second << " " << iter->first << endl; } } Receiving the error "expected primary-expression before '!=' token and for '->' token. Can't seem to understand the error I'm making here. Any ideas?
iter is a type in your code. Should be a variable. typedef map<char*,char*> my_map_t; // alias for a specialized map // declare a variable of needed type my_map_t rtable; // declare iter of type my_map_t::const_iterator for (my_map_t::const_iterator iter=rtable.begin(); iter != rtable.end(); ++iter) { cout << iter->second << " " << iter->first << endl; } // scope of the iter variable will be limited to the loop above
3,018,201
3,018,231
How to Access a Private Variable?
This question isn't meant to sound as blatantly insulting as it probably is right now. This is a homework assignment, and the spec sheet is scarce and poorly designed to say the least. We have a function: double refuel( int liter, GasStation *gs ) { // TODO: Access private variable MaxFuel of gs and decrement. } Sound simple enough? It should be, but the class GasStation comes with no function that accesses the private variable MaxFuel. So how can I access it anyway using the function refuel? I'm not considering creating a function setFuel( int liter ) because the teacher always complains rather energetically if I change his specification. So... I guess I have to do some sort of hack around it, but I'm not sure how to go about this without explicitely changing the only function in GasStation and giving it a parameter so that I can call it here. Any hints perhaps?
Now that sounds like a real lousy homework assignment. Anyway, I can think of three ways to access private data: through public member functions by a friend of the class cheating: #define private public #include "the_class.h" #undef private The first two are legal, but require you to change the class. The last is "non-intrusive" (for some definition of "non-intrusive", anyway), but is definitely illegal (although I have yet to see a compiler were it wouldn't work).
3,018,313
6,930,407
Algorithm to convert RGB to HSV and HSV to RGB in range 0-255 for both
I am looking for color space converter from RGB to HSV, specifically for the range 0 to 255 for both color spaces.
I've used these for a long time - no idea where they came from at this point... Note that the inputs and outputs, except for the angle in degrees, are in the range of 0 to 1.0. NOTE: this code does no real sanity checking on inputs. Proceed with caution! typedef struct { double r; // a fraction between 0 and 1 double g; // a fraction between 0 and 1 double b; // a fraction between 0 and 1 } rgb; typedef struct { double h; // angle in degrees double s; // a fraction between 0 and 1 double v; // a fraction between 0 and 1 } hsv; static hsv rgb2hsv(rgb in); static rgb hsv2rgb(hsv in); hsv rgb2hsv(rgb in) { hsv out; double min, max, delta; min = in.r < in.g ? in.r : in.g; min = min < in.b ? min : in.b; max = in.r > in.g ? in.r : in.g; max = max > in.b ? max : in.b; out.v = max; // v delta = max - min; if (delta < 0.00001) { out.s = 0; out.h = 0; // undefined, maybe nan? return out; } if( max > 0.0 ) { // NOTE: if Max is == 0, this divide would cause a crash out.s = (delta / max); // s } else { // if max is 0, then r = g = b = 0 // s = 0, h is undefined out.s = 0.0; out.h = NAN; // its now undefined return out; } if( in.r >= max ) // > is bogus, just keeps compilor happy out.h = ( in.g - in.b ) / delta; // between yellow & magenta else if( in.g >= max ) out.h = 2.0 + ( in.b - in.r ) / delta; // between cyan & yellow else out.h = 4.0 + ( in.r - in.g ) / delta; // between magenta & cyan out.h *= 60.0; // degrees if( out.h < 0.0 ) out.h += 360.0; return out; } rgb hsv2rgb(hsv in) { double hh, p, q, t, ff; long i; rgb out; if(in.s <= 0.0) { // < is bogus, just shuts up warnings out.r = in.v; out.g = in.v; out.b = in.v; return out; } hh = in.h; if(hh >= 360.0) hh = 0.0; hh /= 60.0; i = (long)hh; ff = hh - i; p = in.v * (1.0 - in.s); q = in.v * (1.0 - (in.s * ff)); t = in.v * (1.0 - (in.s * (1.0 - ff))); switch(i) { case 0: out.r = in.v; out.g = t; out.b = p; break; case 1: out.r = q; out.g = in.v; out.b = p; break; case 2: out.r = p; out.g = in.v; out.b = t; break; case 3: out.r = p; out.g = q; out.b = in.v; break; case 4: out.r = t; out.g = p; out.b = in.v; break; case 5: default: out.r = in.v; out.g = p; out.b = q; break; } return out; }
3,018,418
3,018,475
Open Source Simple Speech Recognition in C++ in Windows
I was wondering, are there any basic speech recognition tools out there? I just want something that can distinguish the difference between "yes" and "no" and is reasonably simple to implement. Most of the stuff out there seems to make you start from scratch, and I'm looking for something more high level. Thanks!
Sphinx3 & PocketSphinx are written in C, so it shouldn't be too hard wrap it for C++. It's still an active project too, which is good.
3,018,511
3,018,602
g++ linker can't find const member function
I have a Point class (with integer members x and y) that has a member function withinBounds that is declared like so: bool withinBounds(const Point&, const Point&) const; and defined like this: bool Point::withinBounds(const Point& TL, const Point& BR) const { if(x < TL.getX()) return false; if(x > BR.getX()) return false; if(y < TL.getY()) return false; if(y > BR.getY()) return false; // Success return true; } and then in another file, I call withinBounds like this: Point pos = currentPlayer->getPosition(); if(pos.withinBounds(topleft, bottomright)) { // code block } This compiles fine, but it fails to link. g++ gives me this error: /home/max/Desktop/Development/YARL/yarl/src/GameData.cpp:61: undefined reference to 'yarl::utility::Point::withinBounds(yarl::utility::Point const&, yarl::utility::Point const&)' When I make the function not const, it links fine. Anyone know the reason why? The linker error looks like it's looking for a non-const version of the function, but I don't know why it would.
It looks like in the calling file, whatever header is included to give the declaration of withinBounds has the incorrect declaration, of a non-const version of the method (note that the undefined reference is to a non-const version). Make sure that your project include directories don't include multiple versions of the header. Also make sure that you did in fact change and save the header as you intended.
3,018,550
3,018,582
How to create pulsating value from 0..1..0..1..0 etc for a given duration?
I'm working on some code where I have a Time object with a member time. Time.time gives me the time since my application started in seconds (float value). Now I want to create a pulsating value between 0 and 1 and then from 1 to 0 again, which continues doing thins untill the application stops. I was thinking to use sin() but don't know what to pass to it as paramters to create this pulsing value. How would I create this pulsating value? Kind regards, Pollux
You mention using sin(), so I guess you want it to pulse continuously between 0 and 1. Something like this will do: float pulse(float time) { const float pi = 3.14; const float frequency = 10; // Frequency in Hz return 0.5*(1+sin(2 * pi * frequency * time)); } 1/frequency = 0.1 second is the period, which is the time between 1's.
3,018,585
3,018,668
How to composite argb image data on top of xrgb image data
I have a pointer to an 32bit argb image's pixel data and a 32bit xrgb image's pixel data. How can I composite the argb on top of xrgb image while making use of the alpha component? Visual Studio 2008 C++ Edit: Is there a quicker (faster processing) way to do the compositing than this: float alpha = (float)Overlay[3] / 255; float oneLessAlpha = 1 - alpha; Destination[2] = (Overlay[2] * alpha + Background[2] * oneLessAlpha); Destination[1] = (Overlay[1] * alpha + Background[1] * oneLessAlpha); Destination[0] = (Overlay[0] * alpha + Background[0] * oneLessAlpha);
Presumably by XRGB you mean a bitmap with four bytes per pixel, but what would be the alpha channel left at some constant value. An obvious starting point would be to draw the XRGB bitmap first, and the RGBA bitmap second. When you draw the second, enable blending (glEnable(GL_BLEND);) and set your blend function with glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);. This way the blending depends only on the alpha channel in the source (the RGBA) and ignores any in the destination (the XRGB bitmap that's already been drawn). Edit: Oops -- somehow I thought I saw some reference to OpenGL, but rereading (and noting the comment) no such thing is there. Doing the job without OpenGL isn't terribly difficult, just generally slower. Let's call the pixels from the two input bitmaps S and D, and the corresponding pixel in the result C. In this case we can compute each pixel in C as: Cr = Sr * Sa + Dr * (1-Sa) Cg = Sg * Sa + Dg * (1-Sa) Cb = Sb * Sa + Db * (1-Sa) This assumes that you normalize (at least) the A channel to the range of 0..1, and that the ARGB bitmap is S and the XRGB is D.
3,018,626
3,018,635
What is the motivation behind C++11 lambda expressions?
I am trying to find out if there is an actual computational benefit to using lambda expressions in C++, namely "this code compiles/runs faster/slower because we use lambda expressions" or is it just a neat development perk open for abuse by poor coders trying to look cool? I understand this question may seem subjective, but I would much appreciate the opinion of the community on this matter.
I don't think it's nearly as much about the computational performance as increasing the expressive power of the language.
3,018,681
3,019,063
wxWidgets running on other machine
I created application which uses wxWidgets library using visual studio 2008. Now I would like to create version which may be run on other machine. Because right now when I want to run It on another machine there is an error: the application failed to start because its side-by-side configuration is incorrect. What can I do to make It work ?
The Event Viewer should have a record showing what DLL was being searched for, what version of that DLL if found in the SxS cache, and what version it was looking for but couldn't find. You'll then want to (for example) include the correct version of that DLL to be installed with your program. Alternatively, just link to virtually everything statically -- it'll make your executable a lot bigger, but eliminate a lot of problems like this relatively painlessly.
3,018,739
3,018,805
Common protected data member in base class?
I have a base class and several derived classes. The derived classes use some common data, can I just put those common data as protected member of the base class? I know the protected member breaks encapsulation sometimes, so I wonder if there is any good approach. Here is a specific example: class Base{ public: virtual void foo() = 0; void printData(); protected: std::vector<std::string> mData; } class Dr1 : public Base{ public: virtual void foo(); //could change mData } class Dr2 : public Base{ public: virtual void foo(); //could change mData } If I put mData into Dr1 and Dr2 as private member, then I need to put it in both of them, and I can not have printData() in Base since printData() need access to mData unless I make printData() virtual and have identical function in both Dr1 and Dr2, which doesn't make much sense to me. Is there a better way to approach this without using protected member? Thank you.
One design to consider is making mData private, and adding protected methods to Base that provide common manipulations to the data that can then be used by Dr1 and Dr2. But there are plenty of times it makes more sense to leave mData as a protected member. The best approach will very much depend on the details of your class.
3,018,821
3,018,836
Simple change results in make: Error 1
Had this: rtable.insert ( pair<string,string>(destination,nhop) ); // route insertion return 0; Changed it to this: if (rtable.insert ( pair<string,string>(destination,nhop)) == 0){ return 0; } First one compiles fine. Second one gives me a make error 1. I can go back and forth all day -- I can't see any issues. Any ideas?
That overload of std::map::insert() returns a std::pair<iterator, bool>. You can't compare that against zero. That bool element tells you whether a new element was inserted; if you want to compare against that you can simply use: if (rtable.insert(pair<string,string>(destination,nhop)).second) return 0
3,019,361
3,019,379
difference between -> and . for member selection operator
Possible Duplicate: what is the difference between (.) dot operator and (->) arrow in c++ in this book i have I'm learning pointers, and i just got done with the chapter about OOP (spits on ground) anyways its telling me i can use a member selection operator like this ( -> ). it sayd that is is like the "." except points to objects rather than member objects. whats the difference, it looks like it is used the same way...
Yeah, it actually does the same thing but for different kind of variables. If you have a pointer you have to use ->, while if you have a real value you will use .. So for example struct mystruct *pointer; struct mystruct var; pointer->field = ... var.field = ... That's not hard at all. Just remember that with a pointer you will need ->, and . otherwise.
3,019,416
3,019,511
How to use the callback method with a c++ directshow sample grabber
I have a sample grabber hooked into my directshow graph, based on this example http://msdn.microsoft.com/en-us/library/dd407288(VS.85).aspx the problem is that it uses one shot and buffers. I want to continuously grab samples, and i'd rather have a callback than i guess polling for the samples. How do use the SetCallback method? SetCallback(ISampleGrabberCB *pCallback, long WhichMethodToCallback) how do I point pCallback to my own method?
I come from a c# background, and thought that at some level i could just pass a reference to a method. This doesn't seem to be case. Instead it requires you create a class the implements its interface that defines the method that it will call. You then pass an instance of the class to the filter in the SetCallback method. Certainly seems long winded in comparison to a delegate or lambda expression Here is an example of a class implementing ISampleGrabberCB class SampleGrabberCallback : public ISampleGrabberCB { public: // Fake referance counting. STDMETHODIMP_(ULONG) AddRef() { return 1; } STDMETHODIMP_(ULONG) Release() { return 2; } STDMETHODIMP QueryInterface(REFIID riid, void **ppvObject) { if (NULL == ppvObject) return E_POINTER; if (riid == __uuidof(IUnknown)) { *ppvObject = static_cast<IUnknown*>(this); return S_OK; } if (riid == __uuidof(ISampleGrabberCB)) { *ppvObject = static_cast<ISampleGrabberCB*>(this); return S_OK; } return E_NOTIMPL; } STDMETHODIMP SampleCB(double Time, IMediaSample *pSample) { return E_NOTIMPL; } STDMETHODIMP BufferCB(double Time, BYTE *pBuffer, long BufferLen) { return E_NOTIMPL; } };
3,019,444
3,020,792
book "Programming Role Playing Games with DirectX 2nd edition" and newer DirectX api
I got the book "Programming Role Playing Games with DirectX 2nd edition" and I notice there are things in the book that are now considered deprecated. There is a whole Section on DirectPlay. And as much as I would like to avoid this section, I am afraid it might screw up the entire engine he is trying to build. So I was just curious to know even though DirectPlay is considered deprecated by XNA, and directX10. Is it possible to use it still in DirectX 9 ??
Sure you can use it. You can write your entire game in DirectX 3 if you want. DirectX 9 includes ALL previous releases. The only issue you will have is finding the headers. TBH, though, you'd be best off ditching it and learning sockets programming instead. Sockets will NEVER go away. They aren't particularly difficult either. At least you wont be learning an unsupported, no-longer documented API. Its also worth noting that there was a reason nobody used Direct Play in the first place ;)
3,019,512
5,294,005
C++0x unique_ptr replaces scoped_ptr taking ownership?
I used to write code like this: class P {}; class Q: public P {}; class A { // takes ownership A(P* p): p_(p) {} scoped_ptr<P> p_; }; A a(new Q); With C++0x, should I rewrite class A as: class A { // takes ownership A(unique_ptr<P>&& p): p_(p) {} unique_ptr<P> p_; };
I've upvoted comonad's answer, but with a caveat: Whenever you want to explicitely disallow move semantics, use a scoped_ptr const unique_ptr. I have not come across any use cases where a const std::unique_ptr is inferior to a boost::scoped_ptr. However I'm open to education on the subject. Edit: Here is a use case of boost::scoped_ptr that I think should fail, but does not. It does fail for std::unique_ptr: #include <iostream> #ifdef USE_UNIQUEPTR #include <memory> typedef std::unique_ptr<int> P; #else // USE_UNIQUEPTR #include <boost/scoped_ptr.hpp> typedef boost::scoped_ptr<int> P; #endif // USE_UNIQUEPTR int main() { P p1(new int(1)); { // new scope #ifdef USE_UNIQUEPTR const P p2(new int(2)); #else // USE_UNIQUEPTR P p2(new int(2)); #endif // USE_UNIQUEPTR swap(p1, p2); // should fail! } std::cout << *p1 << '\n'; } If the promise of boost::scoped_ptr is that its resource will not escape the current scope, then it is not as good at holding that promise as a const std::unique_ptr. If we want to compare const boost::scoped_ptr to const::std::unique_ptr, I have to ask: for what purpose? They seem the same to me, except that a const std::unique_ptr allows customized construction and destruction.
3,019,868
3,019,888
Can I tell direct3d to render with alpha channel?
I need to composite direct3d renders on top of a video feed, the way i have it setup the format i get the data in is 32 bit xrgb with a byte for red green blue and a throw away. Can I get it to render with an alpha channel so i can use it for better blending?
You sure can. Use D3DFMT_A8R8G8B8 for your back buffer. http://msdn.microsoft.com/en-us/library/bb172558(VS.85).aspx
3,019,977
3,020,014
Convert wchar_t to char
I was wondering is it safe to do so? wchar_t wide = /* something */; assert(wide >= 0 && wide < 256 &&); char myChar = static_cast<char>(wide); If I am pretty sure the wide char will fall within ASCII range.
assert is for ensuring that something is true in a debug mode, without it having any effect in a release build. Better to use an if statement and have an alternate plan for characters that are outside the range, unless the only way to get characters outside the range is through a program bug. Also, depending on your character encoding, you might find a difference between the Unicode characters 0x80 through 0xff and their char version.
3,019,979
3,020,030
Microsoft sublanguage string to locale identifier
I can't seem to find a way to convert, or find, a local identifier from a sublanguage string. This site shows the mappings: http://msdn.microsoft.com/en-us/library/dd318693(v=VS.85).aspx I want the user to enter a sublanguage string, such as "France (FR)" and to get the local identifier from this, which in this case would be 0x0484. Or the other way around, if a user enters 0x0480 then to return French (FR). Has anyone encountered this problem before and can point me in the right direction? Otherwise I'm going to be writing a few mapping statements to hard code it and maintain future releases if anything changes. BTW, I'm coding in C++ for Windows platform. Cheers
A good starting point would be the LCIDToLocaleName function and it's opposite - LocaleNameToLCID. Note that these allow converting between LCID and RFC4646 locale name; to get the humanreadable country and language names, use the GetLocaleInfoEx with the LOCALE_SENGLISH* flags. If you need localized names instead of English, use LOCALE_SLOCALIZED* constants instead.
3,020,053
3,020,056
Casting/dereferencing member variable pointer from void*, is this safe?
I had a problem while hacking a bigger project so I made a simpel test case. If I'm not omitting something, my test code works fine, but maybe it works accidentally so I wanted to show it to you and ask if there are any pitfalls in this approach. I have an OutObj which has a member variable (pointer) InObj. InObj has a member function. I send the address of this member variable object (InObj) to a callback function as void*. The type of this object never changes so inside the callback I recast to its original type and call the aFunc member function in it. In this exampel it works as expected, but in the project I'm working on it doesn't. So I might be omitting something or maybe there is a pitfall here and this works accidentally. Any comments? Thanks a lot in advance. (The problem I have in my original code is that InObj.data is garbage). #include <stdio.h> class InObj { public: int data; InObj(int argData); void aFunc() { printf("Inside aFunc! data is: %d\n", data); }; }; InObj::InObj(int argData) { data = argData; } class OutObj { public: InObj* objPtr; OutObj(int data); ~OutObj(); }; OutObj::OutObj(int data) { objPtr = new InObj(data); } OutObj::~OutObj() { delete objPtr; } void callback(void* context) { ((InObj*)context)->aFunc(); } int main () { OutObj a(42); callback((void*)a.objPtr); }
Yes, this is safe. A pointer to any type can be converted to a pointer to void and back again. Note that the conversion to void* is implicit, so you don't need the cast.