question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
1,912,199
1,912,221
Better random algorithm?
I'm making a game in C++ and it involves filling tiles with random booleans (either yes or no) whether it is yes or no is decided by rand() % 1. It doesn't feel very random. I'm using srand with ctime at startup, but it seems like the same patterns are coming up. Are there any algorithms that will create very random ...
True randomness often doesn't seem very random. Do expect to see odd runs. But at least one immediate thing you can do to help is to avoid using just the lowest-order bit. To quote Numerical Recipes in C: If you want to generate a random integer between 1 and 10, you should always do it by using high-order bits,...
1,912,693
1,912,734
segfault when copying an array to a vector in Linux
I'm trying to debug a legacy code written for Linux. Sometimes the application gets a segfault when it reaches the memcpy call in the following method: std::vector<uint8> _storage; size_t _wpos; void append(const uint8 *src, size_t cnt) { if (!cnt) return; if (_storage.size() < _wpos + cnt) _storage.resize(_...
Your code looks good in terms of the data that is written. Are you absolutely sure that you're passing in the right src pointer? What happens when you run the code with a debugger such as gdb? It should halt on the segfault, and then you can print out the values of _storage.size(), src, and cnt. I'm sure you'll find...
1,913,055
1,913,103
Making PNG|jpeg from LaTeX in C or C++
I'm looking for a library (or a cleverer solution) in C or C++ that would make an image file (PNG|jpeg) from LaTeX code. The use of packages is a prerequisite. For now I'm thinking of compiling a .tex file into a .dvi and using dvipng to get a .PNG. There's also the possibility of compiling a .tex file into a .ps file...
I've used the dvipng route several times before, but in python. It's a common path, that lots of people have taken. Here's the code, to give you something to get started, and in case anyone wants Python code. I do realise you asked for C/C++; this is for a starter, or for others. This is for generating equations, but i...
1,913,069
1,913,142
Learning about C++ 0x features
What is a good place to learn about the new C++ 0x features? I understand that they may not have been fully finalized yet but it would be nice to get a head start. Also, what compilers currently support them?
An easy and fun way to learn about it is to watch the C++0x Overview Google Techtalk. Another good source is Bjarne Stroutstrup's C++0x FAQ which covers a huge portion of the new features.
1,913,337
1,913,435
Replacement for vector accepting non standard constructable and not assignable types
I have a class test which isn't standard constructable nor assignable due to certain reasons. However it is copy constructable - on may say it behaves a bit like a reference. Unfortunately I needed a dynamic array of these elements and realized that vector<test> isn't the right choice because the elements of a vector m...
Edit: The below is no longer good practice. If your object supports moving then it will probably fit into a vector (see the std::vector elements requirements for details, in particular the changes for C++17). Consider using Boost's ptr_vector, part of the Boost Pointer Container Library. See in particular advantage #...
1,913,343
1,913,393
How could pairing new[] with delete possibly lead to memory leak only?
First of all, using delete for anything allocated with new[] is undefined behaviour according to C++ standard. In Visual C++ 7 such pairing can lead to one of the two consequences. If the type new[]'ed has trivial constructor and destructor VC++ simply uses new instead of new[] and using delete for that block works fin...
Suppose I'm a C++ compiler, and I implement my memory management like this: I prepend every block of reserved memory with the size of the memory, in bytes. Something like this; | size | data ... | ^ pointer returned by new and new[] Note that, in terms of memory allocation, there is no difference bet...
1,913,496
1,915,020
Behavior of WS_CLIPCHILDREN and InvalidateRect in Windows 7
To reduce flickering I create my parent windows using the WS_CLIPCHILDREN flag and I call InvalidateRect during the WM_SIZE event. This approach has worked well in Windows XP. However, I recently started programming on Windows 7 and I'm now experiencing rendering issues when resizing windows. When resizing a window its...
You can try calling RedrawWindow, passing flags RDW_INVALIDATE and RDW_ALLCHILDREN. Edit: To redraw the background, you can add RDW_ERASE. If you want to redraw the background on the parent but not the children, call both RedrawWindow and InvalidateRect(...,TRUE).
1,913,541
1,913,898
How to save pointer to member in compile time?
Consider the following code template<typename T, int N> struct A { typedef T value_type; // OK. save T to value_type static const int size = N; // OK. save N to size }; Look, it is possible to save any template parameter if this parameter is a typename or an integer value. The thing is that pointer to member is an...
Why using a template? #include <cstdio> struct Foo { int a; int b; } foo = {2, 3}; int const (Foo::*mp) = &Foo::b; int main() { printf("%d\n", foo.*mp); return 0; } The following compiles mp to this on gcc-4.4.1 (I don't have access to MSVC at the moment): .globl mp .align 4 .type ...
1,913,767
1,922,745
What's the fastest way to deserialize a tree in C++
I'm working with a not so small tree structure (it's a Burkhard-Keller-Tree, > 100 MB in memory) implemented in C++. The pointers to the children of each node are stored in a QHash. Each node x has n children y[1] ... y[n], the edges to the children are labeled with the edit distance d(x, y[i]), so using a hash to sto...
Another approach would be to serialize your pointers and restore them when loading. I mean: Serializing: nodeList = collectAllNodes(); for n in nodelist: write ( &n ) writeNode( n ) //with pointers as-they-are. Deserializing: //read all nodes into a list. while ( ! eof(f)) read( prevNodeAddress) readNode( n...
1,913,842
1,913,864
struct sizeof result not expected
I have a a struct defined thusly: typedef struct _CONFIGURATION_DATA { BYTE configurationIndicator; ULONG32 baudRate; BYTE stopBits; BYTE parity; BYTE wordLength; BYTE flowControl; BYTE padding; } CONFIGURATION_DATA; Now, by my reckoning, that struct is 10 bytes long. However, sizeof repor...
Alignment. use #pragma pack(1) ...struct goes here... #pragma pack() I would also recommend reordering things, and if necessary padding then with RESERVED bytes, so that multi-byte integral types will be better aligned. This will make processing faster for tbe CPU, and your code smaller.
1,913,853
1,913,918
Why [] is used in delete ( delete [] ) to free dynamically allocated array ?
I know that when delete [] will cause destruction for all array elements and then releases the memory. I initially thought that compiler wants it just to call destructor for all elements in the array, but I have also a counter - argument for that which is: Heap memory allocator must know the size of bytes allocated an...
Scott Meyers says in his Effective C++ book: Item 5: Use the same form in corresponding uses of new and delete. The big question for delete is this: how many objects reside in the memory being deleted? The answer to that determines how many destructors must be called. Does the pointer being deleted point to a single ...
1,914,337
1,915,349
How can I make QtCreator compile with gsl library?
I am trying to use the GNU Scientific Library (GSL) http://www.gnu.org/software/gsl/ in QtCreator. How can I tell Qt creator to add these flags: http://www.gnu.org/software/gsl/manual/html_node/Linking-programs-with-the-library.html to link correctly?
You need to edit your .pro file and add the extra libs by hand, e.g.: LIBS += -L/usr/local/lib example.o -lgsl -lgslcblas -lm See the QMake documentation for more information.
1,914,416
1,984,617
OpenCV cvNamedWindow not appearing under Fedora
As the title suggests I'm simply trying to get a named window to come up. I've been working with OpenCV for over a year now, and never had this problem before. For some reason, the window never opens. I've tried running some of my old scripts and everything works fine. As a very cut down example, see below #include "cv...
Simply call cvWaitKey(int milliseconds) within the loop. This function notifies the GUI system to run graphics pending events. Your code should be something like: int main(int argc, char** argv) { cvNamedWindow( "video", 0 ); IplImage *im = cvCreateImage( cvSize(200,200), 8, 3 ); while(1) { cvShowImage(...
1,914,606
1,914,615
Is there any generic vesion of HashTable?
I need a class that will work like C++ std::map. More specifically, I need such a behavior: map< string, vector<int> > my_map; Is it possible?
A dictionary is I believe what you want: Dictionary<String, int> dict = new Dictionary<String, int>(); dict.Add("key", 0); Console.WriteLine(dict["key"]); etc, etc MSDN: http://msdn.microsoft.com/en-us/library/xfhwa508.aspx You can specify more or less any type as the key/value type. Including another dictionary, an...
1,914,633
2,063,964
bring malloc() back to its initial state
Do you know if there is a way to bring back malloc in its initial state, as if the program was just starting ? reason : I am developing an embedded application with the nintendods devkitpro and I would like to be able to improve debugging support in case of software faults. I can already catch most errors and e.g. retu...
The only way to get a fresh start is to reload the application from storage. The DS loads everything into RAM which means that the data section is modified in place.
1,914,776
1,915,601
mysql aggregate UDF (user defined function) in C
I need to write an aggregate extension function (implemented in C) for mySQL 5.x. I have scoured the documentation (including browsing sql/udf_example.c) but I do not find anything that is brief, to the point and shows me just what I need to do. This is the problem: I have a C struct (Foo) I have a C function that ta...
Doesn't answer your question but article on MySQL udf is pretty good: http://www.codeproject.com/KB/database/MySQL_UDFs.aspx
1,914,864
1,914,893
Determine an included header files contribution to total file size
I am interested in reducing the file size of my application. It is a MFC/C++ application built with MVC++ in Visual Studio 2008. UPX does a good job of reducing the final exe to about 40% of its original size but I would like to reduce it more. MFC must be statically linked in this project. I have tried some methods ou...
You are probably wrong in this. Removing headers can result in somewhat shorter build times, but as what they contain is mostly declarations (which you will need at some point anyway) they should have little or no effect on the size of the final executable.
1,915,184
2,060,496
GStreamer or DirectShow for Windows development?
I'm implementing a lecture-capture project for a local university. Multiple video streams will arrive at one PC: the presenter's desktop slides, a video camera image of the presenter himself and optionally a digital whiteboard capture. These incoming streams will be managed by a desktop application that displays, trans...
Ok, I'll answer this question myself. The simple answer is: GStreamer! I've experienced no difficulties thus far. To make it work on Windows you need to use the GStreamer Winbuilds. Update (6 months later) Actually I burned myself a little bit on this bet. Later in the project the client specified that the WMV9 codec (...
1,915,520
1,930,943
Asio async and concurrency
I'm writing some code with boost::asio, using asynchronous TCP connections. I've to admit that I have some doubts about it. All these regarding concurrency. Here are some: What happens if I start two or more async_write on the same socket without waiting completion of the first one? Will the handlers (and the async_wr...
I assume from your question that you have a single instance of io_service and you want to call async_write() on it from multiple threads. async_write() ultimately calls the post() method of io_service, which in turn takes a lock and pushes the bits to be written into a work queue, ensuring that the bits won't be writte...
1,915,659
1,915,702
does c++ standard prohibit the void main() prototype?
In section 3.6.1.2 of both C++ Standard 1998 and 2003 editions, An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined. I am not a native English speaker.I do not sure what does"but oth...
The english you quote does prohibit declaring main to return void. It is allowing variation in the arguments that come in, but not in the return type.
1,915,704
1,916,893
Writing concurrently to a file
I have this tool in which a single log-like file is written to by several processes. What I want to achieve is to have the file truncated when it is first opened, and then have all writes done at the end by the several processes that have it open. All writes are systematically flushed and mutex-protected so that I don'...
As suggested by reinier, the problem was not in the way I use the files but in the way the programs behave. The fstreams do just fine. What I missed out is the synchronization between the master and the slave (the former was assuming a particular operation was synchronous where it was not). edit: Oh well, there still w...
1,915,739
1,915,806
Stopping an MFC thread
I understand the problem with just killing the thread directly (via AfxEndThread or other means), and I've seen the examples using CEvent objects to signal the thread and then having the thread clean itself up. The problem I have is that using CEvent to signal the thread seems to require a loop where you check to see i...
Does your thread ever exit? If so, you could set an event in the thread at exit and have the main process wait for that event via waitforsingleevent. This is best to do with a timeout so the main process doesn't appear to lockup when it's closing. At the timeout event, kill the thread via AfxKillThread. You'll have...
1,915,759
1,915,814
Forward declaration and typeid
I would like to check the type of a superclass A against the type of a subclass B (with a method inside the superclass A, so that B will inherit it). Here's what I thought did the trick (that is, the use of forward declaration): #include <iostream> #include <typeinfo> using namespace std; class B; class A { public...
I think that the problem you are trying to solve is much better handled by a virtual method: class A { public: virtual bool Check() { return false; }; } class B : public A { public: // override A::Check() virtual bool Check() { return true; }; } Methods in the base class A should not ...
1,915,829
1,917,084
Learning C when you already know C++?
I think I have an advanced knowledge of C++, and I'd like to learn C. There are a lot of resources to help people going from C to C++, but I've not found anything useful to do the opposite of that. Specifically: Are there widely used general purpose libraries every C programmer should know about (like boost for C++) ...
There's a lot here already, so maybe this is just a minor addition but here's what I find to be the biggest differences. Library: I put this first, because this in my opinion this is the biggest difference in practice. The C standard library is very(!) sparse. It offers a bare minimum of services. For everything el...
1,915,880
1,917,145
boost::bind & boost::function pointers to overloaded or templated member functions
I have a callback mechanism, the classes involved are: class App { void onEvent(const MyEvent& event); void onEvent(const MyOtherEvent& event); Connector connect; } class Connector { template <class T> void Subscribe(boost::function <void (const T&)> callback); } App::App() { connect.Subscribe<M...
I think you need to disambiguate the address of the overloaded function. You can do this by explicitly casting the function pointer to the one with the correct parameters. boost::bind( static_cast<void (App::*)( MyEvent& )>(&App::OnEvent) , this, _1); Similar problem + solution on gamedev.net
1,916,015
1,916,036
If we use the C prefix for classes, should we use it for struct also?
Assuming that a project has been using the C class prefix for a long time, and it would be a waste of time to change at a late stage, and that the person who originally wrote the style guide has been hit by a bus, and that there are no structs in the code already... It's a pretty trivial question, but if a C++ code sty...
If the style guide doesn't specify, I would (probably) use the "structs are classes with all members public"-rule to use C for structs too, yes. Or I would think "hah, here's a loophope to get around that silly initial rule, yay" and not use it. In other words, this is highly subjective.
1,916,039
1,916,049
why would std::string s("??<") output a { instead of ??< as expected?
std::string s("??<"); std::cout << s << std::endl; Why does that output { instead of ??< I'm using Visual Studio 2008. I'm assume it's encoding it but why and what is the encoding called if that is what's happening? This little %#$^*! caused me to look for a bug in my (unit test) code for 30 minutes before I figured ...
Because of trigraphs. These are the supported trigraphs, from the Wikipedia page: ??= → # ??/ → \ ??' → ^ ??( → [ ??) → ] ??! → | ??< → { ??> → } ??- → ~ For Visual Studio, according to the documentation trigraphs are turned off by default (sensibly enough), so check your project/makefiles.
1,916,118
1,916,235
C++ COM C# Mixed Mode Interoperation
I'm trying to understand my options for calling a C# library implementation from unmanaged C++. My top level module is an unmanaged C++ COM/ATL dll. I would like to integrate functionality of an existing managed C# dll. I have, and can recompile the source for both libraries. I understand from reading articles like thi...
How do I go about setting this up? Can I simply change some properties on the existing COM/ATL project to allow use of the C# modules? If you fully control that project, so changing such settings isn't an issue, then sure. All you need is to enable /clr for this project (In project properties, open the "General" page...
1,916,155
1,916,873
base32 conversion in C++
does anybody know any commonly used library for C++ that provides methods for encoding and decoding numbers from base 10 to base 32 and viceversa? Thanks, Stefano
Did you mean "base 10 to base 32", rather than integer to base32? The latter seems more likely and more useful; by default standard formatted I/O functions generate base 10 string format when dealing with integers. For the base 32 to integer conversion the standard library strtol() function will do that. For the reci...
1,916,397
1,916,424
Warning for Missing Virtual Keyword
I had a frustrating problem recently that boiled down to a very simple coding mistake. Consider the following code: #include <iostream> class Base { public: void func() { std::cout << "BASE" << std::endl; } }; class Derived : public Base { public: virtual void func() { std::cout << "DERIVED" << std::endl; } ...
In Visual C++ you can use the override extension. Like this: virtual void func() override { std::cout << "DERIVED" << std::endl; } This will give an error if the function doesn't actually override a base class method. I use this for ALL virtual functions. Typically I define a macro like this: #ifdef _MSC_VER #defin...
1,916,515
1,916,705
How defensive should you be?
Possible Duplicate: Defensive programming We had a great discussion this morning about the subject of defensive programming. We had a code review where a pointer was passed in and was not checked if it was valid. Some people felt that only a check for null pointer was needed. I questioned whether it could be check...
In Code Complete 2, in the chapter on error handling, I was introduced to the idea of barricades. In essence, a barricade is code which rigorously validates all input coming into it. Code inside the barricade can assume that any invalid input has already been dealt with, and that the inputs that are received are good...
1,916,574
1,916,881
How to effectively kill a process in C++ (Win32)?
I am currently writing a very lightweight program so I have to use C++ since it is not bound to .NET framework which drastically increases size of the program. I need to be able to terminate process and to do that I need to get a process handle. Unfortuanately I haven't figured how to do that yet. P.S. I know that to ...
The PID you need for OpenProcess() is not normally easy to get a hold of. If all you got is a process name then you need to iterate the running processes on the machine. Do so with CreateToolhelp32Snapshot, followed by Process32First and loop with Process32Next. The PROCESSENTRY32.szExeFile gives you the process nam...
1,916,701
1,916,717
A simple C++ framework for Win32 Windows Applications?
Is there a simple/small framework (Other than .NET) which allows you to create windowed applications with C++ under Win32. Just like a little DLL I can include with my app. It should have basic functions like creating a window , buttons , text edits and handling them.
WTL is a set of lightweight templates that make writing Win32 windowing code quite easy (to the extend C++/Win32 can be easy).
1,916,736
1,917,071
Is there a way to do something to static members on process end?
I have a class that uses libxml2. It has static members which are used to hold context for a schema file and its parser. I'm using valgrind, and it's complaining that memory is not deallocated in connection with the schema context. This is because you need to free that memory yourself. However, since these context ...
Declare another class within your XML-using class. In its destructor, clean up your static members. Now give the outer class another static member of the inner class type. By virtue of having a non-trivial destructor, it will get cleaned up as the program exits, and thus your other values will get cleaned up, too. clas...
1,916,782
1,916,985
Static library links in wxWidgets statically, but apps using my lib still require wxwidgets
Hopefully someone can help me out here. I'm using Visual Studio 2005 and creating a static library that links in wxWidgets statically. I have: compiled wxWidgets statically according to their guide included the lib directory in my "Additional Library Directories" property added all of the wxWidget libs in my "Addition...
It is the link step in the build process that pulls dependent libs in : When you build a static library, it does NOT pull in any recursive dependencies as there is no link step. So both - your - and wx's - static libs need to be present then for the final application to link.
1,916,813
1,916,884
Handling of references in C++ templates
I currently have a function template, taking a reference, that does something in essence equivalent to: template <typename T> void f(T& t) { t = T(); } Now, I can call: int a; f(a); To initialize my variable a. I can even do: std::vector<int> a(10); f(a[5]); However, this will fail: std::vector<bool> a(10); f(a[5...
I think specialising f for std::vector<bool>::reference is your only option. Note that using std::vector<bool> is probably a bad idea in the first place (the std::vector<bool> specialisation is deprecated for future versions of the c++ language) so you could just use std::deque<bool> instead.
1,917,289
1,917,471
Call unmanaged C++ VS 6.0 MFC dll from C#
I have an unmanaged C++ MFC dll that was developed in VS 6.0. I would like to use it in my C# app. I'm trying to use PInvoke. Here is the C++ code: // testDll.cpp : Defines the entry point for the DLL application. // #include "stdafx.h" extern "C" { BOOL APIENTRY DllMain( HANDLE hModule, DWOR...
TestDll.dll probably can't load one of it's dependent DLL's. Try loading your TestDll.dll file in the Depends (Dependency Walker) utility. Depends should be installed with VC 6, under Microsoft Visual Studio 6.0 Tools. That will show you what dependencies the DLL has and will flag if one of the dependencies failed....
1,917,344
1,917,530
Writing a test case that checks for memory leaks in C++
NOTE: THIS IS NOT HOMEWORK IT IS FROM A PRACTICE EXAM GIVEN TO US BY OUR PROFESSORS TO HELP US PREPARE FOR OUR EXAM I'm currently studying for a programming exam. On one of the sample tests they gave us we have the following question: Suppose you have been given a templated Container that holds an unordered collection ...
What if you create a class to use as the template parameter that will add 1 to a global variable in it's constructor and decrease that same global variable by 1 in it's destructor. Then you can perform whatever tests you want on the container (create it, fill it and empty it, delete it, etc) and check for memory leaks ...
1,917,411
1,917,461
What's the result if I use delete p instead of delete [] p for an array?
Possible Duplicates: Why is there a special new and delete for arrays? ( POD )freeing memory : is delete[] equal to delete ? What's the result if I use delete p instead of delete [] p for an array? I met two answers for this problem. 1 only the first element will be freed. 2 there comes to a catastrophic end. My que...
It is undefined behavior. What this means is that the standard gurantees to the writers of the memory management library that certain pre-conditions exist (In this case that arrays will be deleted with delete []). If you break these pre-conditions then the memory management library could fail in some way. How it fail...
1,917,415
1,917,468
c++ boost regex which element was true
The answer to this may be a simple no, but here goes... I'm currently using the boost function regex_match to evaluate a string against a regex value. Instead of just returning T/F, is there a way to find out which element of multiple joined statements evaluated to true? For example: ^a$|^z$|^p$ a --> 0 z --> 1 f --> ...
Enclose them in capturing parentheses, then test which sub-expression matched. (^a$)|(^z$)|(^p$) match_results m; regex_match(..., m); a -> m[1].matched z -> m[2].matched p -> m[3].matched Update: You might be able to improve on it by making a single capture group and testing the result, e.g.: ^([azp])$ ... if ('a' ...
1,917,590
1,920,381
Dialog application with LISTBOX
I'm creating an S60 application that will have a main dialog with a listbox of 5 or so items. but i keep receiving a message : "application app1 closed" when trying to run the application on the emulator. This is my resource file (app1.rss)content : RESOURCE DIALOG r_dialog { flags=EAknDialogSelectionList; ...
You are experiencing a panic. You should enable extended panic code to see which panic you are getting, and then refer to the system panic reference documentation to see what it means. In this particular case, at least your listbox item format is not correct. EAknCtSingleGraphicListBox enum value corresponds to CAknSin...
1,917,718
1,917,736
Are multiple conditional operators in this situation a good idea?
I just saw this block of code on the Wikipedia article on conditional operators: Vehicle new_vehicle = arg == 'B' ? bus : arg == 'A' ? airplane : arg == 'T' ? train : arg == 'C' ? car : arg == 'H' ? horse : ...
I have used this type of construction many times. As long as it's formatted nicely (i.e. not all on one line, making it unreadable), I don't see a problem with it.
1,917,789
1,919,117
How to use HTTPS with HttpReceiveHttpRequest()?
I'm using the Windows HTTP API to process web service requests in C++ (not .NET) and everything works just fine for HTTP requests. When I change the URLs I'm expecting with HttpAddUrl to https://example.com:443/foo/bar my tests from Internet Explorer no longer connect. My code does not get called at all and the calls t...
You'll need to install the SSL cert in the machine store (mmc.exe, add Certificates snap-in, manage the Computer account, import the cert). Then have a go with httpconfig- it's a GUI version of httpcfg/netsh http that's much easier. I have this tool on every server I maintain that has SSL certs. Once that's configured,...
1,917,890
1,918,335
Using stdout/stderr/stdin streams behind haskell's FFI
I'm developing a small haskell program that uses an external static library I've developed in C++. It accesses the lib through ghc's FFI (foreign function interface). Inside this library I would like to do some output to the console. However, it looks to me like the c++ side of things does not have a correct handle to ...
Your problem does appear to be that libstdc++ is not being initialized. I'm not entirely sure why — -lstdc++ is sufficient on my system — but see if it works the other way around. Main.hs: {-# LANGUAGE ForeignFunctionInterface #-} module Main where foreign export ccall "Main_main" main :: IO () foreign import ccall dr...
1,917,909
1,918,257
Detecting application hang
I have a very large, complex (million+ LOC) Windows application written in C++. We receive a handful of reports every day that the application has locked up, and must be forcefully shut down. While we have extensive reporting about crashes in place, I would like to expand this to include these hang scenarios -- even ...
The answer is simple: SendMessageTimeout! Using this API you can send a message to a window and wait for a timeout before continuing; if the application responds before timeout the is still running otherwise it is hung.
1,918,065
1,918,119
Passing a reference of a base class to another function
Here is the problem i am facing, does anyone have solution? Class A: public class B { // I want to pass a reference of B to Function } void ClassC::Function(class& B) { //do stuff }
The way you are declaring the class is wrong: class A : public B // no more class keyword here { }; // note the semicolon void ClassC::Function(const B &b) // this is how you declare a parameter of type B& { } You simply need to pass the object of type A to the Function. It'll work. It's good to declare the paramete...
1,918,236
1,918,750
C# Child Process from Legacy C++ App Windowing Problems
We have a c++ legacy application and have been extending it with c# applets that are invoked using COM from the parent c++ app. They bring up windows that are not modal. Moreover, I think these .NET windows are not proper children of the c++ application, since EnumChildWindows misses them, and EnumWindows finds them....
Would it work if the C# windows actually were child windows? It might be possible to accomplish that by passing the parent HWND as an argument to the C# COM object, and then using PInvoke to call SetParent on the C# windows. (I've never done this, but it sounds at least as safe as fighting with ShowWindow and the ta...
1,918,263
1,918,397
Reading Pixels of Image in C++
How to open and read the pixels of an image in c++? Read them in the form of X, Y and to know the color.
If you are going to be working with images you should look into the OpenCV library, it has pretty much everything you need to work with images. OpenCV 2.0 came out a couple of months ago and its very friendly with C++.
1,918,360
1,918,390
Are there any Regression Tests coded in C/C++ to test all the functionality of CString (ATL/MFC)?
I am trying to do a comparison of CString from ATL/MFC to a custom CString implementation and I want to make sure that all the functionality in the custom implementation matches that of the ATL/MFC implementation. The reason we have a custom CString implementation is so that we can use it on *nix and Windows platforms....
Personally I cannot think of any. However if I were doing it I would encode all the use cases I have for it and make sure I owned a test to cover it. Also on windows do you delegate to the supplied implementaton or your own? If you delegated you could find your tests more useful as they could highlight differences. Goo...
1,918,385
1,918,477
How do I over-allocate memory using new to allocate variables within a struct?
So I have a couple of structs... struct myBaseStruct { }; struct myDerivedStruct : public myBaseStruct { int a, b, c, d; unsigned char* ident; }; myDerivedStruct* pNewStruct; ...and I want to dynamically allocate enough space so that I can 'memcpy' in some data, including a zero-terminated string. The size o...
You can allocate any size you want with malloc: myDerivedStruct* pNewStruct = (myDerivedStruct*) malloc( sizeof(myDerivedStruct) + sizeof_extra data); You have a different problem though, in that myDerivedStruct::ident is a very ambigous construct. It is a pointer to a char (array), then the structs ends with th...
1,918,498
1,918,508
Filling a Partially Rounded Rectangle with GDI+
I have a rounded rectangle that I make like so dc.RoundRect(textBorder, CPoint(20, 20)); Later on I draw a line through it about 1/3 of the way down. dc.LineTo(textBorder.right, textBorder.top + 15); Now I would like to fill just the part above the line with a solid color. In other words I need to fill a partially...
Have you tried using a combination of CreateRoundRectRegion and then FillRgn to fill the non-rectangular area? This the example given in the docs for CreateRoundRectRegion: CRgn rgnA, rgnB, rgnC; VERIFY(rgnA.CreateRoundRectRgn( 50, 50, 150, 150, 30, 30 )); VERIFY(rgnB.CreateRoundRectRgn( 200, 75, 250, 125, 50, 50 )...
1,918,502
1,918,504
Very weird errors when linking (LNK1000)?
Error 1 fatal error LNK1000: Internal error during IncrBuildImage MFC_Test MFC_Test Why do I get this weird error every 2nd time I compile?
It is a bug in link.exe. Apply this hotfix https://connect.microsoft.com/VisualStudio/Downloads/DownloadDetails.aspx?DownloadID=11399
1,918,563
1,918,792
split a string using find_if
I found the following code in the book "Accelerated C++" (Chapter 6.1.1), but I can't compile it. The problem is with the find_if lines. I have the necessary includes (vector, string, algorithm, cctype). Any idea? Thanks, Jabba bool space(char c) { return isspace(c); } bool not_space(char c) { return !isspace(...
There is no problem in the code you posted. There is a very obvious problem with the real code you linked to: is_space and space are member functions, and they cannot be called without an instance of Split2. This requirement doesn't make sense, though, so at least you should make those functions static. (Actually it do...
1,918,723
1,918,739
std::vector of known sequences
I'm trying to learn C++ by doing everything "the C++ way". I'm writing a program where I have all of these known values (at compile time). Here is my problem: In my constructor I want to check to see if a passed value(an int) is one of 2,4,8,16 or 32 and throw an error elsewise. I've though about: making a C style ...
What's wrong with: if (!(n == 2 || n == 4 || n == 8 || n == 16 || n == 32)) { // no! } If you want the "C++ way", a static array should do, with find: template <typename T, size_t N> T* endof(T (&pArray)[N]) { return &pArray[0] + N; } static const int OkNumbers[] = {2, 4, 8, 16, 32}; static const int* OkNumbe...
1,918,911
1,931,513
Better boost asio deadline_timer example
I'm after a better example of the boost::asio::deadline_timer The examples given will always time out and call the close method. I tried calling cancel() on a timer but that causes the function passed into async_wait to be called immediately. Whats the correct way working with timers in a async tcp client?
You mention that calling cancel() on a timer causes the function passed to async_wait to be called immediately. This is the expected behavior but remember that you can check the error passed to the timer handler to determine if the timer was cancelled. If the timer was cancelled, operation_aborted is passed. For exam...
1,919,032
1,920,786
C++ Builder - Spawn TThreads On the Fly
I'm looking for the ability to spawn a thread or function so that it returns immediately to the calling line and continue on with the program but continues with the thread work. For instance, if you call Form.ShowDialog(), it will create a modeless form that has its own UI thread. Is there a way to do this (no form) w...
I don't know exactly why you don't want to create a TThread subclass, but if you are using the Windows version of C++ Builder you can use the _beginthreadex function (declared in process.h).
1,919,125
1,919,180
Programmatically adding a directory to Windows PATH environment variable
I'm writing a Win32 DLL with a function that adds a directory to the Windows PATH environment variable (to be used in an installer). Looking at the environment variables in Regedit or the Control Panel after the DLL has run shows me that my DLL has succeeded in adding the path to HKEY_LOCAL_MACHINE\SYSTEM\CurrentContro...
It turns out there really isn't anything new under the sun. This has already been done before, at least once. By me. I created a DLL very much like what you describe for exactly the same purpose (for use in modifying the path from an NSIS installer). It gets used by the Visual Leak Detector installer. The DLL is called...
1,919,251
1,919,279
Display image in opengl
I am fairly new to openGL. I have a 3d game that I have running, and it seems to go fairly well. What I would like to do is display an image straight onto the screen, and I am not sure the easiest way to do that. My only idea is to draw a rectangle right in front of the screen and use the image as the texture. It seems...
I would recommend setting up OpenGL for 2D rendering via gluOrtho2d(); then, load the image into a texture and, as you said, draw it to the screen by creating a polygon and binding the texture to it. A good example can be found here.
1,919,388
1,919,411
Testing for a non-null pointer, and returning null otherwise
I'm wondering whether it's considered okay to do something like this. if ( p_Pointer != NULL ) { return p_Pointer; } else { return NULL; } Without the else, whatever. The point is that if the pointer is null, NULL is going to be returned, so it would seem pointless wasting a step on this. However, it seems useful ...
It's "okay" to do this, i.e. there's nothing wrong with it, although it's not very useful. If you're stepping through in a debugger, you should be able to display the value of p_Pointer anyway. It's similar to if( flag == TRUE ) { return TRUE; } else { return FALSE; } rather than just return flag;
1,919,546
1,921,262
Sun Studio C++ "is not terminated with a newline" warning - how to suppress?
I have ported a fair bit of code from Win to Solaris, one of the issues I have - I am getting a heaps of warnings: Warning: Last line in file is not terminated with a newline. I like warnings - but because of the sheer amount of those I am afraid I could miss more important one. Which compiler (cc) option should I sp...
Although i think Martin's solution of fixing the original source files would be preferable, if you really want to disable the warnings then this page describes the -erroff flag which you can use to disable specific warnings. In your case add -erroff=E_NEWLINE_NOT_LAST to the CC command line to switch the newline warni...
1,919,571
1,919,588
whats the difference between c compiler and c++ compiler of microsoft c/c++ compiler?
I could compile the void main() as c++ source file with microsoft c/c++ compiler 14.00 (integrated with visual studio 2005).So does it means that the compiler does not conform to the c++ standard on the main function prototype? Is the microsoft c/c++ compiler only one compiler,that is,it is only one c++ compiler?Beca...
I could compile the void main() The valid signatures of main are: int main(void); // no parameters int main(int, char **); // parameterized Everything else is not standard. The standard does allow an implementation to allow alternate signatures of main(). Is the microsoft c/c++ compiler only one compiler,that is,i...
1,919,574
1,919,595
calculating expression without using semicolon
Given the expression by input like 68+32 we have to evaluate without using a semicolon in our program. If it will be something inside the if or for loop? Reference : https://www.spoj.pl/problems/EXPR2/
You can use if and the comma operator, something like this: if( expr1, expr2, expr3, ... ) {} It would be equivalent to expr1; expr2; expr3; ... To use variables without any warnings you can define a function the recieves the data types you need that you call from your main, like so: void myFunc(int a, double b) { ...
1,919,608
1,921,403
Checking for null before pointer usage
Most people use pointers like this... if ( p != NULL ) { DoWhateverWithP(); } However, if the pointer is null for whatever reason, the function won't be called. My question is, could it possibly be more beneficial to just not check for NULL? Obviously on safety critical systems this isn't an option, but your program...
Don't make it a rule to just check for null and do nothing if you find it. If the pointer is allowed to be null, then you have to think about what your code does in the case that it actually is null. Usually, just doing nothing is the wrong answer. With care it's possible to define APIs which work like that, but this r...
1,919,626
1,919,647
Can I get a non-const C string back from a C++ string?
Const-correctness in C++ is still giving me headaches. In working with some old C code, I find myself needing to assign turn a C++ string object into a C string and assign it to a variable. However, the variable is a char * and c_str() returns a const char []. Is there a good way to get around this without having to ro...
I guess there is always strcpy. Or use char* strings in the parts of your C++ code that must interface with the old stuff. Or refactor the existing code to compile with the C++ compiler and then to use std:string.
1,919,657
1,919,699
C++ static library link with shared lib. Compiling would be fine?
Here is a C++ project, and its lib dependency is Hello.exe -> A.so -> B.a B.a -> A.so Hello.exe depends on B.a and A.so, and B.a depends on A.so. GCC compiler will link Hello.exe successful? And if there is a b.cc file in B.a which includes a header file a.h of A.so, and also uses some interfaces of A.so...
A static library is just a collection of object files created from compiled .c/.cpp files. It cannot have link relationships. You will need to specify link dependencies to both A.so and B.a when you compile Hello.exe off the top of my head it would be something like gcc -o Hello.exe B.a A.so As a side note you should ...
1,920,430
1,920,481
C++ array initialization
is this form of intializing an array to all 0s char myarray[ARRAY_SIZE] = {0} supported by all compilers? , if so, is there similar syntax to other types? for example bool myBoolArray[ARRAY_SIZE] = {false}
Yes, this form of initialization is supported by all C++ compilers. It is a part of C++ language. In fact, it is an idiom that came to C++ from C language. In C language = { 0 } is an idiomatic universal zero-initializer. This is also almost the case in C++. Since this initalizer is universal, for bool array you don't ...
1,920,687
1,921,236
Passing information between two seperate programs
I want to pass a value of an input variable in my program lets say#1 to another program #2 and i want #2 to print the data it got to screen, both are needed to be written in c++. The this will be on Linux.
In response to your comment to Roopesh Majeti's answer, here's a very simple example using environment variables: First program: // p1.cpp - set the variable #include <cstdlib> using namespace std;; int main() { _putenv( "MYVAR=foobar" ); system( "p2.exe" ); } Second program: // p2.cpp - read the variable ...
1,920,906
1,931,302
OpenCV with QT on Maemo 5 (N900)
Since the presentation by Eero Bragge at theAmterdam devdays about QT / QT-Creator I've been looking for an excuse to try my hands at mobile development. Now this excuse has arrived in the form of the Nokia N900, my new phone! My other hobby is computer vision, so my first Idea's for applications to try and build lie i...
"I see that improvements to the OpenCV port are were among the Meamo google summer of code 2009 ideas that didn't make the cut. Is there work being done there?" The project was not select, and AFAIK the people involved didn't carry the project. OpenCV seems to work under Maemo5 according to the discussion here: http://...
1,920,910
1,920,927
What is the best way to take generically a container in C++ using interfaces (i.e. equivalent of taking IEnumerable as argument in C#)
I would like a C++ constructor/method to be able to take any container as argument. In C# this would be easy by using IEnumerable, is there an equivalent in C++/STL ? Anthony
The C++ way to do this is with iterators. Just like all the <algorithm> functions that take (it begin, it end, ) as first two parameters. template <class IT> T foo(IT first, IT last) { return std::accumulate(first, last, T()); } If you really want to go passing the container itself to the function, you have to use...
1,920,969
1,921,010
Is there an easy way to push variables onto the stack for later retrieval
I have a member function of an object that is typically used in an iterative manner but occasionally in a recursive manner. The function is basically following the path of a stream of water downhill, and under certain conditions the stream could split. In order to support the occasional recursion I have to push the s...
I guess the obvious way would be to create a copy of your entire object and the do the recursive call on that. This way, each branch has it's own state, and you compiler does the stack management for you. Basically, a method has to be reentrant in order to be safely used in recursion. That is not the case here, since y...
1,921,231
1,922,749
Maintaining a recent files list
I would like to maintain a simple recent files list on my MFC application that shows the 4 most recently used file names. I have been playing with an example from Eugene Kain's "The MFC Answer Book" that can programmatically add strings to the Recent Files list for an application based on the standard Document/View arc...
I recently did that using MFC, so since you seems to be using MFC as well maybe it will help: in: BOOL MyApp::InitInstance() { // Call this member function from within the InitInstance member function to // enable and load the list of most recently used (MRU) files and last preview // state. SetRegist...
1,921,232
1,924,467
Just-In-Time Derivation
There's a less common C++ idiom that I've used to good effect a few times in the past. I just can't seem to remember if it has a generally used name to describe it. It's somewhat related to mixins, CRTP and type-erasure, but is not specifically any of those things. The problem is found when you want to add some impleme...
I'd definitely consider this to be a mixin, as would Bruce Eckel (http://www.artima.com/weblogs/viewpost.jsp?thread=132988). In my opinion one of the things that makes this a mixin is that it's still single inheritance, which is different from using MI to achieve something similar.
1,921,607
1,921,640
A Reliable way to Identify a computer by its ip address
I have a network of computers that they will connect to the a server with DHCP, so I don't know what Ip address a computer will get when I connects to the server. If 192.168.0.39 for example is connected to the server can I identify the real computer behinde this ip address? ( I can install an external application on e...
If you are responsible for the DHCP server, you can configure it to hand out a specific IP to a specific MAC. Having done that, you can be reasonably confident of that mapping -- it is possible to spoof MACs, so if you are worried about security, you'll need a much more heavy duty approach. If this is a casual applic...
1,921,817
1,921,917
Template type deduction in C++ for Class vs Function?
Why is that automatic type deduction is possible only for functions and not for Classes?
In specific cases you could always do like std::make_pair: template<class T> make_foo(T val) { return foo<T>(val); } EDIT: I just found the following in "The C++ Programming Language, Third Edition", page 335. Bjarne says: Note that class template arguments are never deduced. The reason is that the flexibilit...
1,921,948
1,922,030
ILockBytesOnHGlobal WriteAt performance decreases over time
I've created ILockBytesOnHGlobal and I write 64k of data repeatedly. What I've noticed is that WriteAt performance decreases over the time. What could be the reason for the performance slow down? Does it have to do with stream growth? Here is what I'm doing (in C#) public override void Write(byte[] buffer, int off...
CreateILockBytesOnHGlobal documentation says that it uses GlobalReAlloc to increase the memory block. GlobalReAlloc copies the data from the old memory block to the new (and larger) memory block, so this causes performance to go down over time.
1,921,961
1,921,988
Should a person new to windowed applications study X, GTK+, or what?
Let's say the factors for valuing a choice are the library of widgets available, the slope of the learning curve, and the degree of portability (platforms it works on). As far a language binding goes, I'm using C++. Thanks!
Pure X is quite hardcore these days, and not very portable. Basically, there are three major toolkits: GTK+ (and C++ wrapper GTKmm) Qt wxWidgets which are pretty comparable, so which to choose is a matter of taste. All three run on major three operating systems, although GTK+ on Mac and Windows is little bit awkward....
1,922,069
1,970,470
WinPE 2.0 (Vista) - Looking for a solution for BrowseForFolder using VBSCRIPT & HTA application
I am creating an HTA application to be run inside of a WinPE 2.0 environment. The purpose of this HTA app is to prompt the user to select a back-up location. I am currently using BrowseForFolder to prompt the user folder location. Script works fine in Vista. However, this does not work in winpe 2.0 - and a dialog ap...
After weeks and weeks... I have found (and tested) a solution using Autoit, download here: http://www.autoitscript.com/autoit3/ Autoit will allow you to create a standalone executable BrowseForFolder dialog using their "BASIC-like scripting language designed for automating the Windows GUI and general scripting" By doin...
1,922,294
1,923,059
Using Unicode font in C++ console app
How do I change the font in my C++ Windows console app? It doesn't seem to use the font cmd.exe uses by default (Lucida Console). When I run my app through an existing cmd.exe (typing name.exe) it looks like this: http://dathui.mine.nu/konsol3.png which is entierly correct. But when I run my app seperatly (double-clic...
For Vista and above, there is SetCurrentConsoleFontEx, as already has been said. For 2K and XP, there is an undocumented function SetConsoleFont; e.g. read here. typedef BOOL (WINAPI *FN_SETCONSOLEFONT)(HANDLE, DWORD); FN_SETCONSOLEFONT SetConsoleFont; .......... HMODULE hm = GetModuleHandle(_T("KERNEL32.DLL")); SetCon...
1,922,325
1,928,950
Find a cycle in an undirected graph (boost) and return its vertices and edges
I need a functions thats find a cycle in an undirected graph (boost) and returns its vertices and edges. It needs only return the vertices/edges of one cycle in the graph. My question is - what is the best way to do this using with boost? I am not experienced using it.
If you want to find a cycle, then using depth first search should do just fine. The DFS visitor has a back_edge function. When it's called, you have an edge in the cycle. You can then walk the predecessor map to reconstruct the cycle. Note that: There's the strong_components function, to find, well, strong components ...
1,922,455
1,923,014
thread synchronization - delicate issue
let's i have this loop : static a; for (static int i=0; i<10; i++) { a++; ///// point A } to this loop 2 threads enters... i'm not sure about something.... what will happen in case thread1 gets into POINT A , stay there, while THREAD2 gets into the loop 10 times, but after the 10'th loop after incrementing i's v...
You have to realize that an increment operation is effectively really: read the value add 1 write the value back You have to ask yourself, what happens if two of these happen in two independent threads at the same time: static int a = 0; thread 1 reads a (0) adds 1 (value is 1) thread 2 reads a (0) adds 1 (value is 1...
1,922,580
1,922,730
Import a DLL with C++ (Win32)
How do I import a DLL (minifmod.dll) in C++ ? I want to be able to call a function inside this DLL. I already know the argument list for the function but I don't know how to call it. Is there a way of declaring an imported function in C++ like in C# ?
The c# syntax for declaring an imported function is not available in c++. Here are some other SO questions on how to use DLLs: Explicit Loading of DLL Compile a DLL in C/C++, then call it from another program Calling functions in a DLL from C++ Call function in c++ dll without header How to use dll's? Is this a good ...
1,922,986
1,923,058
Running in the Terminal a build made in XCode, how?
Im creating a project in Xcode using OpenCV as a framework. It works great with the Build&Run option from Xcode, but now I need to run it in the Terminal and it gives me this error: dyld: Library not loaded: @executable_path/../Frameworks/OpenCV.framework/Versions/A/OpenCV Referenced from: /Users/Victor/Documents/PFC/s...
You need to run it from the build directory rather than the Release directory (assuming Frameworks is a directory in blob)
1,923,091
1,923,375
UTF-16 codecvt facet
Extending from this questions about locales And described in this question: What I really wanted to do was install a codecvt facet into the locale that understands UTF-16 files. I could write my own. But I am not a UTF expert and as such I am sure I would get it nearly correct; but it would break at the most inconvenie...
I'm not sure if by "resources on the Web" you meant available free of cost, but there is the Dinkumware Conversions Library that sounds like it will fit your needs—provided that the library can be integrated into your compiler suite. The codecvt types are described in the section Code Conversions.
1,923,201
1,923,221
CString join method?
I need to concatenate a list of MFC CString objects into a single CSV string. .NET has String.Join for this task. Is there an established way to do this in MFC/C++?
The + operator is overloaded to allow string concatenation. I'd suggest take a look at the documentation on MSDN: Basic CString Operations has the following example: CString s1 = _T("This "); // Cascading concatenation s1 += _T("is a "); CString s2 = _T("test"); CString message = s1 + _T("big ") + s2; // Messa...
1,923,317
1,923,504
Can BSTR's hold characters that take more than 16 bits to represent?
I am confused about Windows BSTR's and WCHAR's, etc. WCHAR is a 16-bit character intended to allow for Unicode characters. What about characters that take more then 16-bits to represent? Some UTF-8 chars require more then that. Is this a limitation of Windows? Edit: Thanks for all the answers. I think I understand...
UTF-8 is not the encoding used in Windows' BSTR or WCHAR types. Instead, they use UTF-16, which defines each code point in the Unicode set using either 1 or 2 WCHARs. 2 WCHARs gives exactly the same amount of code points as 4 bytes of UTF-8. So there is no limitation in Windows character set handling.
1,923,664
1,924,029
Simulating low memory using C++
I am debugging a program that fails during a low memory situation and would like a C++ program that just consumes LOT of memory. Any pointers would help!
Allcoating big blocks is not going to work. Depending on the OS you are not limited to the actual physical memory and unused large chunks could be potentially just swap out to the disk. Also this makes it very hard to get your memory to fail exactly when you want it to fail. What you need to do is write your own vers...
1,923,780
1,923,800
Using typedef from inside a template as template argument type
I'm trying to do something like this (completely synthetic example, because the real code is a bit to convoluted): enum MyInfoType { Value1, Value2 }; template<typename T> struct My_Type_Traits {}; template<> struct My_Type_Traits<int> { typedef MyInfoType InfoType; }; template<typename T> class Wrap { ...
You need to use the typename keyword: like typename My_Type_Traits<T>::InfoType to let the compiler know you're referring to a nested type.
1,924,070
1,924,096
Don't give away your internals? [C++]
I am reading book called "C++ coding standard" By Herb Sutter, Andrei Alexandrescu and in chapter 42 of this book is an example:(chapter is short so I'm taking the liberty and pasting part of it) Consider: class Socket { public: // … constructor that opens handle_, destructor that closes handle_, etc. … int Get...
I think what you're missing is that a handle — even though it's represented by an int in the type system — is a reference to something. This isn't returning some informational value — it's returning the object's internal reference to a system resource. The class should manage this handle itself, and the handle should b...
1,924,255
1,924,341
How to embed WebKit into my C/C++/Win32 application?
The solutions I have found are irrelevant: someone used WebKit in a Delphi project someone used it with Java there is QtWebKit (about:blank demo app takes 44 megs) .Net port of it GTK+ port I need a guide how to embed WebKit instance into a pure C/C++ application under Win32.
Brent Fulgham has put lots of work into producing a Windows Cairo port of WebKit, which doesn't rely on Apple's proprietary backend stuff (e.g. CoreGraphics, CoreFoundation, CFNetwork). I believe that is what you are after. The details aren't entirely collated in one place, but there is some information in the Trac wik...
1,924,530
1,926,432
mixing cout and printf for faster output
After performing some tests I noticed that printf is much faster than cout. I know that it's implementation dependent, but on my Linux box printf is 8x faster. So my idea is to mix the two printing methods: I want to use cout for simple prints, and I plan to use printf for producing huge outputs (typically in a loop). ...
The direct answer is that yes, that's okay. A lot of people have thrown around various ideas of how to improve speed, but there seems to be quite a bit of disagreement over which is most effective. I decided to write a quick test program to get at least some idea of which techniques did what. #include <iostream> #inclu...
1,924,844
1,924,983
std::map of member function pointers?
I need to implement an std::map with <std::string, fn_ptr> pairs. The function pointers are pointers to methods of the same class that owns the map. The idea is to have direct access to the methods instead of implementing a switch or an equivalent. ( I am using std::string as keys for the map ) I'm quite new to C++, so...
This is about the simplest I can come up with. Note no error checking, and the map could probably usefully be made static. #include <map> #include <iostream> #include <string> using namespace std; struct A { typedef int (A::*MFP)(int); std::map <string, MFP> fmap; int f( int x ) { return x + 1; } int ...
1,925,237
1,925,274
Control USB port's power?
Does anybody know how to control USB pins on a certain USB port? I think it is definately possible in assembler but what about C++ or C#? I want to be able to use USB battery as a power supply for an LED or something like that. So then a program would power it on and power it off making it flash. I know it sounds poin...
USB is not trivial, so I guess you'll have some problems (mis)using it. You would be /much/ better off (IMHO) with standard serial ports, which have been used for stuff like that for ages, with plenty of examples available. If you don't have serial port available on your target machine, you can use USB->Serial interfac...
1,925,264
1,925,281
MSVC9: How do I view a location in memory?
I'm pretty sure I'm overlooking something totally obvious, but I want to view the raw contents of a point in memory under MSVC9, but I can't find a location in the UI where I can punch in a memory address. How can this be done?
A couple of places: When you're debugging, go to Debug->Windows->Memory In the watch window, just cast a memory address to whatever you want: (char*)0xdeadbeef
1,925,341
1,925,373
Problems passing argument to a const parameter
Say I have a function that takes a const reference to a pointer... Example: void Foo( const Bar *&p_Thing, ); and I pass a pointer Bar *blah = NULL; // Initialized when program starts up to the function Foo( blah ); I may encounter a compiler error like this invalid initialization of reference of type 'const Bar*&' ...
This is what you want: void Foo( Bar * const &p_Thing ); Then it becomes a const-reference to a Bar * pointer, which has the lovely feature of compiling.
1,925,403
1,925,426
Implementing a z buffer in a software rasterizer
as a homework assignment, we're writing a software rasterizer. I've noticed my z buffering is not working as well as it should, so I'm trying to debug it by outputting it to the screen. (Black is near, white is far away). However, I'm getting peculiar values for the z per vertex. This is what I use to transform the poi...
To normalize the Z values you have to define a near clipping plane and a far clipping plane. Then you normalize Z such that its 0 at the near plane and 1 at the far plane. However, you would usually do that after projection. It looks like your last line is where projection occurs. A number of other things: You comput...
1,925,422
1,925,435
How do I convert System::WideString to a char* and vice versa?
I have a situation where I need to compare a char* with a WideString. How do I convert the WideString to a char* in C++?
You can use the wcstombs function. size_t wcstombs( char * mbstr, const wchar_t * wcstr, size_t max );
1,925,523
1,925,544
Is There an Archiving Library Without Dependencies? (C/C++)
Hey, I'm looking for an archiving library that functions like GNU's tar, but without any dependencies. I need some sort of archiving format to manage resources in my game engine and am still iffy about rolling my own.
Take a look at the BSD libarchive
1,925,876
1,926,077
What kind of applications should be rewritten to use OpenCL?
Mac OS X 10.6 comes with OpenCL, but how many applications could have better performances if they would be rewritten to use OpenCL? What kind of applications should be rewritten to use OpenCL?
My company is using OpenCL for scientific calculations. While I'm not part of the development team which is using it I can tell you a few things they're using it to do: large scale data processing of images, imagine reconstruction, and massively parallelization of previously written scientific code. Basically, OpenCL...
1,925,887
1,925,900
Splitting up lines into ints
I have a file that I read from, it contains a bunch of lines each with a different number of integers, I'm having trouble splitting it up into a vector of a vector of ints. This is my current code. std::vector<int> read_line() { std::vector<int> ints; int extract_int; while((const char*)std::cin.peek() != "...
The problem is your (const char *)std::cin.peek() != "\n" cast. casts are evil; try to avoid using them. The following code works: std::vector<int> read_line() { std::vector<int> ints; int extract_int; while(std::cin.peek() != '\n' && std::cin.peek() != -1) { std::cin >> extract_int; int...
1,926,067
1,930,132
What alignment guarantees can I expect for arrays in a struct?
I've got a lightweight templated class that contains a couple of member objects that are very rarely used, and so I'd like to avoid calling their constructors and destructors except in the rare cases when I actually use them. To do that, I "declare" them in my class like this: template <class K, class V> class MyClass ...
There's no guarantee that you'll get the appropriate alignment. Arrays are in general only guaranteed to be aligned for the member type. A char array is aligned for storage of char. The one exception is that char and unsigned char arrays allocated with new are given maximum alignment, so that you can store arbitrary ty...