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,251,625
1,251,684
Non-destructive parsing and modifying of HTML elements in C++
I have a need to do some simple modifications to HTML in C++, preferably without completely rewriting the HTML, such as what happens when I use libxml2 or MSHTML. In particular I need to be able to read, and then (potentially) modify, the "src" attribute of all "img" elements. I need it to be robust enough to be able t...
Regular expressions aren't recommended for HTML because they don't handle nested tags well. They should be fine for this purpose.
1,252,011
1,253,100
Is there a generic way to iterate over a specific variable in a group of objects?
Lets say I have a linked list with a bunch of different data in it. class Node { public: Node* next; AAA dataA; BBB dataB; CCC dataC; }; Is there a way I make one iterator that would iterate over whatever variable I specify (rather than making three separate ones for each variable). I understand that ...
I think I've found a way to do pretty much what I want based on rstevens' suggestion. I looked up some stuff on class member pointers and was able to skip the middleman accessor class by doing this: template <typename T> class iterator { private: Node *current; T Node::*var; public: iterator() : cu...
1,252,049
1,252,069
C++ LNK1120 and LNK2019 errors: "unresolved external symbol WinMain@16"
I'm trying to do another exercise from Deitel's book. The program calculates the monthly interest and prints the new balances for each of the savers. As the exercise is part of the chapter related to dynamic memory, I'm using "new" and "delete" operators. For some reason, I get these two errors: LNK2019: unresolved ex...
Go to "Linker settings -> System". Change the field "Subsystem" from "Windows" to "Console".
1,252,117
1,252,137
How to avoid infinite recursion in C++ class templates
I have a matrix class with the size determined by template parameters. template <unsigned cRows, unsigned cCols> class Matrix { ... }; My program uses matrices of a few sizes, typically 2x2, 3x3, and 4x4. By setting the matrix size with template parameters rather than run-time parameters allows the compiler to do...
You need to provide a specialization for a Matrix that has no rows or no columns. E.g. template<unsigned cRows> class Matrix< cRows, 0 > { Matrix<cRows - 1, 0> Reduced() { return Matrix<cRows - 1, 0>(); } }; template<unsigned cCols> class Matrix< 0, cCols > { Matrix<0, cCols - 1> Reduced() { return Matrix<0, ...
1,252,201
1,260,371
Any good C/C++ web toolkit?
I've been looking around and came across the WT toolkit, Is it stable? Any good? I was stumped on how to go about this in C++, given the lack of libraries and resources concerning web developement. (CGI/Apache) The purpose of my application is to populate some data from a Sybase ASE15 database running GNU/Linux & Apach...
Give this one a look. I never much liked Wt's design. But then, I'm kind of an anti-framework guy. http://cppcms.sourceforge.net/wikipp/en/page/main
1,252,224
1,252,268
Using boost::tokenizer with string delimiters
I've been looking boost::tokenizer, and I've found that the documentation is very thin. Is it possible to make it tokenize a string such as "dolphin--monkey--baboon" and make every word a token, as well as every double dash a token? From the examples I've only seen single character delimiters being allowed. Is the libr...
It looks like you will need to write your own TokenizerFunction to do what you want.
1,252,333
1,252,341
Constructor with references not properly assigning?
I'm trying to write a simple color class that's supposed to be as versatile as possible. Here's what it looks like: class MyColor { private: uint8 v[4]; public: uint8 &r, &g, &b, &a; MyColor() : r(v[0]), g(v[1]), b(v[2]), a(v[3]) {} MyColor(uint8 red, uint8 green, uint8 blue, uint8 alpha = 255) : r(v[0]), g(v[1]), b...
Unfortunately, you can't do constructor forwarding at the moment in C++. The issue is here: MyColor(uint8 vec[]) : r(v[0]), g(v[1]), b(v[2]), a(v[3]) { MyColor(vec[0], vec[1], vec[2], vec[3]); } What this actually does is to bind the references to the member vector v and then in the body of the constructor create...
1,252,362
1,253,218
Is it safe to read past the end of an array?
Let's say I have a constructor like this: MyColor(uint8 vec[]) { r = vec[0]; g = vec[1]; b = vec[2]; a = vec[3]; } But I call it like this (3 elements instead of 4): uint8 tmp[] = {1,2,3}; MyColor c(tmp); But now vec[3] is undefined... is it safe to assign this value to a? If not, there's no nice workaround to check ...
if you dont want to use vector try this... MyColor(uint8 (&vec)[3]) { r = vec[0]; g = vec[1]; b = vec[2]; } MyColor(uint8 (&vec)[4]) { //... } uint8 a1[] = {1,2,3}; MyColor c1(a1); uint8 a2[] = {1,2,3,4}; MyColor c2(a2); uint8 a3[] = {1,2,3,4,5}; MyColor c3(a3); // error you dont have to include the arra...
1,252,680
1,252,703
OpenGL Windowing Library for 2009
Trying to decide on a library for creating a window and capturing user input for my OpenGL app, but there are just way too many choices: GLUT (win32) FreeGLUT OpenGLUT SFML GLFW SDL FLTK OGLWFW Clutter Qt Others? GLUT is simply outdated. I liked GLFW but it seems you can't set the window position before displaying it...
I'd go for Qt. Nice general purpose library + opengl support
1,252,712
1,252,721
About fork system call and global variables
I have this program in C++ that forks two new processes: #include <pthread.h> #include <iostream> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <cstdlib> using namespace std; int shared; void func(){ extern int shared; for (int i=0; i<10;i++) shared++; cout<<"Process "<<getpi...
The OS is using virtual memory and similar techniques to ensure that each process sees different memory cells (virtual or read) at the same addresses; only memory that's explicitly shared (e.g. via shm) is shared, all memory by default is separate among separate processes.
1,252,786
1,252,798
How to know a certain disk's format(is FAT32 or NTFS)
I am programing under windows, c++, mfc How can I know disk's format by path such as "c:\". Does windows provide such APIs?
The Win32API function ::GetVolumeInformation is what you are looking for. From MSDN: GetVolumeInformation Function BOOL WINAPI GetVolumeInformation( __in_opt LPCTSTR lpRootPathName, __out LPTSTR lpVolumeNameBuffer, __in DWORD nVolumeNameSize, __out_opt LPDWORD lpVolumeSerialNumber, __o...
1,252,976
1,252,996
How to handle multiple keypresses at once with SDL?
been getting myself familiar with OpenGL programming using SDL on Ubuntu using c++. After some looking around and experimenting I am starting to understand. I need advice on keyboard event handling with SDL. I have a 1st person camera, and can walk fwd, back, strafe left and right and use the mouse to look around which...
A good approach will be to write a keyboard ("input") handler that will process input events and keep the event's state in some sort of a structure (associative array sounds good - key[keyCode]). Every time the keyboard handler receives a 'key pressed' event, it sets the key as enabled (true) and when it gets a key do...
1,252,992
1,253,004
How to escape a string for use in Boost Regex
I'm just getting my head around regular expressions, and I'm using the Boost Regex library. I have a need to use a regex that includes a specific URL, and it chokes because obviously there are characters in the URL that are reserved for regex and need to be escaped. Is there any function or method in the Boost library ...
. ^ $ | ( ) [ ] { } * + ? \ Ironically, you could use a regex to escape your URL so that it can be inserted into a regex. const boost::regex esc("[.^$|()\\[\\]{}*+?\\\\]"); const std::string rep("\\\\&"); std::string result = regex_replace(url_to_escape, esc, rep, boost::match_defaul...
1,253,245
1,254,562
Installing Libboost 1.38 on Ubuntu 8.10
Is there a way to Install Libboost 1.38 on Ubuntu 8.10? The highest version in my repositories is 1.35. It has been suggested that there may be some repositories I could add to accomplish this, but my searches haven't yielded anything. Do I have to resort to source code? If so, what is the best way to accomplish this...
You can either Upgrade to Jaunty (Ubuntu 9.04) which has 1.37. You can even incrementally upgrade to just its boost libraries (google for apt-pinning) use a more advanced method I often use: download the Debian package sources from Debian unstable (currently 1.38 with 1.39 in the NEW queue and available "real soon now...
1,253,307
1,253,472
Creating planar shadows with 4x3 matrices?
Was just wondering how I would go about creating a planar shadow from a 4x3 matrix, all online demos I've seen use 4x4 matrices instead.
I guess that this is done by projecting a 3D object onto a plane, which essentially needs a fourth coordinate to represent infinity. If you only use 3 coordinates, you can only represent |R^3. However, for projections like shadows you will need full 3-space, thus including infinity - so you need the fourth coordinate. ...
1,253,398
1,253,416
Pass Bitmap object to unmanaged code
I have the following function in C++ managed (ref) class: public static void Transform(Bitmap^ img); I want to call it from C# managed code. What I do is this: Bitmap image = new Bitmap(100, 100); MyClass.Transform(image); Is this correct, or do I need to use fixed statement? If so, then how? Thank you.
You need to lock the bitmap's backing memory as shown here.
1,253,610
1,253,746
Floating point addition: loss-of-precision issues
In short: how can I execute a+b such that any loss-of-precision due to truncation is away from zero rather than toward zero? The Long Story I'm computing the sum of a long series of floating point values for the purpose of computing the sample mean and variance of the set. Since Var(X) = E(X2) - E(X)2, it suffices to ...
There's another single-pass algorithm which rearranges the calculation a bit. In pseudocode: n = 0 mean = 0 M2 = 0 for x in data: n = n + 1 delta = x - mean mean = mean + delta/n M2 = M2 + delta*(x - mean) # This expression uses the new value of mean variance_n = M2/n # Sample variance varian...
1,253,670
1,253,686
Why do round() and ceil() not return an integer?
Once in a while, I find myself rounding some numbers, and I always have to cast the result to an integer: int rounded = (int) floor(value); Why do all rounding functions (ceil(), floor()) return a floating number, and not an integer? I find this pretty non-intuitive, and would love to have some explanations!
The integral value returned by these functions may be too large to store in an integer type (int, long, etc.). To avoid an overflow, which will produce undefined results, an application should perform a range check on the returned value before assigning it to an integer type. from the ceil(3) Linux man...
1,253,856
1,254,190
Using CreateCompatibleDC with mapping modes other than MM_TEXT
I have a visual C++ application that uses a CView derived class to render its display, which is primarily 3d vector data and true type text. The mapping mode used is either MM_ANISOTROPIC or MM_LOMETRIC. I can't use MM_TEXT as I use the same code for printing and plotting of the data and also have to overcome non-squ...
You probably need to also call SetWindowExt and SetViewportExt. I have definitely used MM_ISOTROPIC with bitmap DCs before and it worked OK (don't have the code to hand as it was since ported to GDI+)
1,253,859
1,253,882
Can virtual functions be used in return values?
I was a little surprised that the following code did not work as expected: #include "stdio.h" class RetA { public: virtual void PrintMe () { printf ("Return class A\n"); } }; class A { public: virtual RetA GetValue () { return RetA (); } }; class RetB : public RetA { public: virtual void PrintMe () { pri...
Polymorphic behavior does not work by value, you need to return pointers or references for this to work. If you return by value you get what is known as "slicing" which means that only the parent part of the object gets returned, so you've successfully striped a child object into a parent object, this is not safe at al...
1,253,928
1,276,199
Extracting Glyph Kerning Information C++
After asking my previous question about Uniscribe glyph kerning, and not yet receiving an answer, plus further reading on google etc, it seems Uniscribe may not support extracting glyph kerning information from a font. I therefore have a simple followup question - are there any good examples (preferably with some C++ c...
OpenType fonts have two different ways to specify kerning information, both of which are optional: The kern table, inherited from TrueType. This table supplies kerning pair information (i.e. how much you should horizontally offset a particular pair of characters). Microsoft provides specs for this table and also supp...
1,254,056
1,254,103
What are the available methods in C++ std library, where can I see/read them?
Where can I see all the available methods in std library ? Since, I can include vector,algorithm in my program, can I see header/source files for this library to see how it is implemented ? eg. I know we can use push_back() method in vector, but where can I see all the methods for vector, and similarly for others libra...
If you want to check the source out, have a look into /usr/include/c++/x.x/vector you'll probable need to redirect your research in this directory (depeding on the class you are looking at): /usr/include/c++/x.x/bits For instance, string class is a typedef, and the underlying type is basic_string you will find in /usr/...
1,254,116
1,255,174
Building a call table to template functions in C++
I have a template function where the template parameter is an integer. In my program I need to call the function with a small integer that is determined at run time. By hand I can make a table, for example: void (*f_table[3])(void) = {f<0>,f<1>,f<2>}; and call my function with f_table[i](); Now, the question is if th...
You can create a template that initializes a lookup table by using recursion; then you can call the i-th function by looking up the function in the table: #include <iostream> // recursive template function to fill up dispatch table template< int i > bool dispatch_init( fpointer* pTable ) { pTable[ i ] = &function<i>...
1,254,196
1,254,212
How to delete folder into recycle bin
I am programing under C++, MFC, windows. I want to delete a folder into recycle bin. How can I do this? CString filePath = directorytoBeDeletePath; TCHAR ToBuf[MAX_PATH + 10]; TCHAR FromBuf[MAX_PATH + 10]; ZeroMemory(ToBuf, sizeof(ToBuf)); ZeroMemory(FromBuf, sizeof(FromBuf)); lstrcpy(FromBuf, ...
The return value from SHFileOperation is an int, and should specify the error code. What do you get?
1,254,244
1,255,558
Need access to "NtSetUuidSeed" from a non-LocalSystem process
I was trying to get a Uuid via NtAllocateUuids or simply calling UuidCreateSequential, but Windows wasn't able to get an Ethernet or token-ring hardware address for my laptop. And so, when the system is booting, windows sets the UuidSeed to a random number instead of a given MAC. --> uniqueness is guaranteed only until...
ImpersonateLoggedOnUser worked fine with a token handle returned from: HANDLE GetLSAToken() //duplicate a system token from the "System" process or BOOL CreatePureSystemToken(HANDLE &hToken) //create a new system token http://www.codeproject.com/KB/system/RunUser.aspx CoreCode.cpp
1,254,335
1,254,376
Where to download GNU C++ compiler
Can anyone suggest me where to download a GNU c++ compiler, which I can use in Ubuntu and also on Windows with Netbeans IDE, and also GNU tools.
If you are using any Linux/Unix/Solaris OS it is available unless you have explicitly not installed. That said, if you still wish to install GNU C++ compiler, use this command sudo aptitude install build-essential and if you wish to download it on your windows, steps are here on Minimalist GNU for Windows
1,254,433
1,254,580
Mixing Objective-C and C++ code
I have an Objective-C/C++ application which uses functionality that is provided by a C++ library. One of the C++ classes includes an enum like this: class TheClass { public: [...] enum TheEnum { YES, NO, }; [...] }; Including (using #import -if that matters-) a header file with the above class declaration in...
YES and NO are predefined constants in Objective-C, declared in the objc.h header. You should be able to prevent the preprocessor to expand the "YES" and "NO" macro's. This can be done by locally #undeffing them. But technically, if you're using a language keyword as an identifier, you can expect trouble. You won't w...
1,254,777
1,254,793
static cast versus dynamic cast
Possible Duplicate: Regular cast vs. static_cast vs. dynamic_cast I don't quite get when to use static cast and when dynamic. Any explanation please?
Use dynamic_cast when casting from a base class type to a derived class type. It checks that the object being cast is actually of the derived class type and returns a null pointer if the object is not of the desired type (unless you're casting to a reference type -- then it throws a bad_cast exception). Use static_cas...
1,254,840
1,254,998
Should I remove QDebug header for release?
I have a Qt Application and I use qDebug message for my application. However I have gotten lazy and left in a load of: #include <QDebug> in my header files. Should I remove them for a production deployment and what benefit will it give?
You shouldn't remove the header inclusion. If you do so, every statement involving qDebug might give a compiler error. Instead, define the symbol QT_NO_DEBUG_OUTPUT when compiling for release. qDebug will do nothing when that symbol is defined and (hopefully) the compiler will optimize away the calls to a function that...
1,255,087
1,255,138
Is there a C++ Almanac?
some of you may know the Java Almanac : http://www.exampledepot.com/ where a lot of code snippets exist for a day-to-day use.(like reading a file etc.) I'm currently using C++ and i was just curios if there exists something similar ?
There are some good examples and tutorials on the Josuttis site. The examples are from the The C++ Standard Library - A Tutorial and Reference book.
1,255,157
1,255,197
char array assignment and management
I'm supposed to write a library in c++ that should handle the connections to the kad network. I'm trying to build a packet accordant to those used by aMule&co. And I really can't understand the difference between this code: buffer = "\xe4\x20\x02"; and, for example, this code: char p_buffer[36]; p_buffer[0] = 0xe4; p_...
Your first code sample is roughly equivalent to: static const char buffer_internal[4] = { 0xe4, 0x20, 0x02, 0x00 }; buffer = buffer_internal; The two differences here are: The buffer is null-terminated The buffer is unmodifiable. Attempting to modify it is likely to crash. Your second sample allocates a 36-byte modi...
1,255,249
1,255,308
I cant find any documentation for g_io_channel_win32_make_pollfd
Is there a documentation available for g_io_channel_win32_make_pollfd? I want to use this function to create FDs on Windows for IPC between the main thread and a separate thread. It is only briefly mentioned here and doesn't really explain how to use it.
Here's the source code, and there's also a testcase that uses it. Documentation is available in the header it's declared in. If that documentation doesn't appear in the manual, you might want to file a bug with the glib people - it's probably being excluded from the documentation generator due to a bug of some sort.
1,255,366
1,255,377
How can I append data to a std::string in hex format?
I have an existing std::string and an int. I'd like to concatenate the ASCII (string literal) hexadecimal representation of the integer to the std::string. For example: std::string msg = "Your Id Number is: "; unsigned int num = 0xdeadc0de; //3735929054 Desired string: std::string output = "Your Id Number is: 0xdead...
Use a stringstream. You can use it as any other output stream, so you can equally insert std::hex into it. Then extract it's stringstream::str() function. std::stringstream ss; ss << "your id is " << std::hex << 0x0daffa0; const std::string s = ss.str();
1,255,430
1,255,801
How can I provide access to this buffer with CSingleLock?
I have these two methods for thread-exclusive access to a CMyBuffer object: Header: class CSomeClass { //... public: CMyBuffer & LockBuffer(); void ReleaseBuffer(); private: CMyBuffer m_buffer; CCriticalSection m_bufferLock; //... } Implementation: CMyBuffer & CSomeClass::LockBuffer() { m_bufferLo...
Use an object that represents the buffer. When this obejct is initialized get the lock and when it is destroyed release the lock. Add a cast operator so it can be used in place of the buffer in any function call: #include <iostream> // Added to just get it to compile struct CMyBuffer { void doStuff() {std::cout << ...
1,255,545
1,255,583
interfaces for templated classes
I'm working on a plugin framework, which supports multiple variants of a base plugin class CPlugin : IPlugin. I am using a boost::shared_ptr<IPlugin> for all reference to the plugins, except when a subsystem needs the plugin type's specific interface. I also need the ability to clone a plugin into another seprate objec...
You can easily write : class CPluginMgr; class IPlugIn .. { friend CPluginMgr; ... }; Only a predefinition is needed for friend.
1,255,559
4,655,887
Integrate ITK (Insight Toolkit) into own project
i am having problems integrating ITK - Insight Toolkit into another image processing pipeline. ITK itself is a medical image processing toolkit and uses cmake as build system. My image pipeline project uses cmake as well. According to the user manual of ITK it is favorable to use the "UseITK.cmake" file in the build (o...
I don't know if you're still having the problem, but here's an easy way: Build the ITK project, and then "make install" (or build the INSTALL.vcproj project in VS), and it will write to a directory you pass as CMAKE_INSTALL_PREFIX while configuring your project. This directory will contain /bin, /lib and /include. You ...
1,255,576
1,255,904
What is good practice for generating verbose output?
what is good practice for generating verbose output? currently, i have a function bool verbose; int setVerbose(bool v) { errormsg = ""; verbose = v; if (verbose == v) return 0; else return -1; } and whenever i want to generate output, i do something like if (debug) std::cout << "de...
The simplest way is to create small class as follows(here is Unicode version, but you can easily change it to single-byte version): #include <sstream> #include <boost/format.hpp> #include <iostream> using namespace std; enum log_level_t { LOG_NOTHING, LOG_CRITICAL, LOG_ERROR, LOG_WARNING, LOG_INFO,...
1,255,919
1,256,218
boost::ifind_first with std::string objects
I am trying to use boost string algorithms for case insensitive search. total newbie here. if I am using it this way, I get an error. std::string str1("Hello world"); std::string str2("hello"); if ( boost::ifind_first(str1, str2) ) some code; Converting to char pointers resolves the problem. boost::ifind_first( (char*...
You need to use boost::iterator_range. This works: typedef const boost::iterator_range<std::string::const_iterator> StringRange; std::string str1("Hello world"); std::string str2("hello"); if ( boost::ifind_first( StringRange(str1.begin(), str1.end()), StringRange(str2.begin(), str2.end())...
1,255,945
1,256,570
C# vs. C++ in a cross-platform project
My team is planning to develop an application that is initially targeted for Windows but will eventually be deployed cross-platform (Mac, Linux and potentially embedded devices). Our decision is whether to use C#/.NET or generic C++ (with Qt as the user interface library). We’re projecting that by using C#, we can de...
Despite all the potential cross platform capabilities of Mono, today, C++/Qt is simply a much more mature option than either C#/WinForms or C#/Gtk# for cross-platform purposes. Any productivity gains you would get by using a higher-level language would likely be offset by dealing with limitations of Mono.
1,256,191
1,256,230
Why do libraries implement their own basic locks on windows?
Windows provides a number of objects useful for synchronising threads, such as event (with SetEvent and WaitForSingleObject), mutexes and critical sections. Personally I have always used them, especially critical sections since I'm pretty certain they incur very little overhead unless already locked. However, looking a...
Libraries aren't implementing their own locks. That is pretty much impossible to do without OS support. What they are doing is simply wrapping the OS-provided locking mechanisms. Boost does it for a couple of reasons: They're able to provide a much better designed locking API, taking advantage of C++ features. The Win...
1,256,240
1,256,280
Why is Boost scoped_lock not unlocking the mutex?
I've been using boost::mutex::scoped_lock in this manner: void ClassName::FunctionName() { { boost::mutex::scoped_lock scopedLock(mutex_); //do stuff waitBoolean=true; } while(waitBoolean == true ){ sleep(1); } //get on with the thread's activities } Basically it sets wait...
The scoped_lock should indeed be released at the end of the scope. However you don't lock the waitBoolean when you're looping on it, suggesting you don't protect it properly other places as well - e.g. where it's set to false, and you'll end up with nasty race conditions. I'd say you should use a boost::condition_varia...
1,256,246
1,256,273
Address of register variable
In C, we cannot use & to find out the address of a register variable but in C++ we can do the same. Why is it legal in C++ but not in C? Can someone please explain this concept in-depth.
Here's an excerpt from Section 6.7.1 (footnote 101) of the C99 standard (pdf): The implementation may treat any register declaration simply as an auto declaration. However, whether or not addressable storage is actually used, the address of any part of an object declared with storage-class specifier register cannot be...
1,256,395
1,256,407
stl vector.push_back() abstract class doesn't compile
Let's say I have an stl vector containing class type "xx". xx is abstract. I have run into the issue where the compiler won't let me "instantiate" when i do something like the following: std::vector<xx> victor; void pusher(xx& thing) { victor.push_back(thing); } void main() { ; } I assume this is because the ...
When you use push_back, you are making a copy of the object and storing it in the vector. As you surmised, this doesn't work since you can't instantiate an abstract class, which is basically what the copy-construction is doing. Using a pointer is recommended, or one of the many smart-pointer types available in librari...
1,256,584
1,256,687
c++ strange c0000005 error
I am working on a project that can start a program on the winlogon desktop. The program works perfectly while debugging but when I start it outside the ide it fails strangly with the infamous c0000005 error. The weirdest thing though is it doesn't seem to occur on any particular line. Here is the code: #include "stdafx...
I think the problem lies within the LPSERVICE_STATUS xyz = (LPSERVICE_STATUS)malloc(sizeof(LPSERVICE_STATUS)); ControlService(schs,SERVICE_CONTROL_STOP,xyz); part. The last argument xyz to ControlService is used by that API to return status information about the service. You are actually passing a pointer to a pointer...
1,256,614
1,498,792
Catching a WM_NOTIFY message from a custom ListCtrl
My application is c++, and is a combination of MFC and ATL. The part I'm working with here is MFC. I have a custom list control class in one of my dialogs which inherits from CListCtrl. I'm trying to add a handler for the LVN_ITEMCHANGED message so I can update the rest of the dialog form, which is dependant on the con...
I've moved this question to stackoverflow.com/questions/1272398 The answer is posted there.
1,256,768
1,256,898
C++: 2D arrays vs. 1D array differences
I have an array of float rtmp1[NMAX * 3][3], and it is used as rtmp1[i][n], where n is from 0 to 2, and i is from 0 to 3 * NMAX - 1. However, I would like to convert rtmp1 to be rtmp1[3 * 3 * NMAX]. Would addressing this new 1D array as rtmp1[3 * i + n] be equivalent to rtmp1[i][n]? Thanks in advance for the clarificat...
rtmp1[i][n] is equivalent to rtmp1[i*NMAX + n] See http://www.cplusplus.com/doc/tutorial/arrays/, where your NMAX is their width.
1,256,803
1,256,923
Using abstract class as a template type
I'm still pretty new to c++ (coming over from java). I have a stl list of type Actor. When Actor only contained "real" methods there was no problem. I now want to extend this class to several classes, and have a need to change some methods to be abstract, since they don't make sense as concrete anymore. As I expected (...
You can not handle this directly: As you can see when the class is abstract you can not instanciate the object. Even if the class where not abstract you would not be able to put derived objects into the list because of the slicing problem. The solution is to use pointers. So the first question is who owns the pointer (...
1,256,963
1,256,988
If MessageBox()/related are synchronous, why doesn't my message loop freeze?
Why is it that if I call a seemingly synchronous Windows function like MessageBox() inside of my message loop, the loop itself doesn't freeze as if I called Sleep() (or a similar function) instead? To illustrate my point, take the following skeletal WndProc: int counter = 0; LRESULT CALLBACK WndProc(HWND hwnd, UINT ms...
The MessageBox() and similar Windows API functions are not blocking the execution, like an IO operation or mutexing would do. The MessageBox() function creates a dialog box usually with an OK button - so you'd expect automatic handling of the window messages related to the message box. This is implemented with its own ...
1,257,115
1,257,375
how to find allocated memory in linux
Good afternoon all, What I'm trying to accomplish: I'd like to implement an extension to a C++ unit test fixture to detect if the test allocates memory and doesn't free it. My idea was to record allocation levels or free memory levels before and after the test. If they don't match then you're leaking memory. What I've ...
I'd have to agree with those suggesting Valgrind and similar, but if the run-time overhead is too great, one option may be to use mallinfo() call to retrieve statistics on currently allocated memory, and check whether uordblks is nonzero. Note that this will have to be run before global destructors are called - so if y...
1,257,161
1,257,179
Array Allocation Subscript Number
Quick question regarding how memory is allocated. If someone were to allocate 20 chars like this: char store[20]; does this mean that it allocated 20 char type blocks of memory, or that it allocated char type blocks of memory starting with 0 and ending with 20. The difference is that the first example's range would be...
It means it allocated one block of memory large enough to hold 20 chars (from index 0 to 19)
1,257,182
1,257,253
Only 2 digits in exponent in scientific ofstream
So according to cplusplus.com when you set the format flag of an output stream to scientific notation via of.setf(ios::scientific) you should see 3 digits plus and a sign in the exponent. However, I only seem to get 2 in my output. Any ideas? Compiled on Mac OS using GCC 4.0.1. Here's the actual code I am using: o...
I believe cplusplus.com is incorrect, or at least is documenting a particular implementation - I can't see any other online docs which specifically state the number of exponent digits which are displayed - I can't even find it in the C++ specification. Edit: The C++ Standard Library: A Tutorial and Reference doesn't ex...
1,257,219
1,257,263
C++ "conversion loses qualifiers" compile error
I ran into an interesting problem while debugging SWIG typemaps today. Anyone care to enlighten me why Visual C++ 2008 throws a "conversion loses qualifiers" error when converting from ourLib::Char * to const ourLib::Char * &? I thought Type * -> const Type * was a trivial conversion, and (when calling functions) Lvalu...
Say you had the following function: void test( const char*& pRef) { static const char somedata[] = { 'a' ,'b', 'c', '\0'}; pRef = somedata; } If you passed in a non-const char*, then when test() returned the compiler would have lost the fact that what p is pointing to is const. It's essentially the same reaso...
1,257,267
1,257,366
Is it legal C++ to pass the address of a static const int with no definition to a template?
I'm having trouble deciding whether not this code should compile or if just both compilers I tried have a bug (GCC 4.2 and Sun Studio 12). In general, if you have a static class member you declare in a header file you are required to define it in some source file. However, an exception is made in the standard for stati...
To be a well formed program you stil have to have the defintion of the static variable (without an initializer in this case) if it actually gets used, and taking the address counts as a use: C++2003 Standard: 9.4.2 Static data members Paragraph 4 (bold added) If a static data member is of const integral or const e...
1,257,493
1,257,506
Given text in a #define, can it somehow be passed to a template?
Say I have a macro, FOO(name), and some template class Bar<> that takes one parameter (what type of parameter is the question). Everytime I call FOO with a different name, I want to get a different instantiation of Bar. The Bar<> template doesn't actually need to be able to get at the name internally, I just need to be...
Depending on where you intend to use this macro (namespace or class scope would work), you could create a tag type and use that: template<typename T> class Bar { //... stuff }; #define FOO(name) struct some_dummy_tag_for_##name {}; Bar<some_dummy_tag_for_##name> If this doesn't work, maybe you can "declare" those na...
1,257,507
1,257,514
What does this mean const int*& var?
I saw someone using this in one answer: void methodA(const int*& var); I couldn't understand what the argument means. AFAIK: const int var => const int value which can't be changed const int* var => pointer to const int, ie *var can't be changed but var can be changed const int& var => reference to const int, ie va...
It is a reference to a pointer to an int that is const. There is another post somewhat related, actually, here. My answer gives a sorta of general algorithm to figuring these things out. This: const int& *var has no meaning, because you cannot have a pointer to reference. If the const's and pointers are getting in the ...
1,257,638
1,264,991
Variable sized structs with trailers
I posted on this topic earlier but now I have a more specific question/problem. Here is my code: #include <cstdlib> #include <iostream> typedef struct{ unsigned int h; unsigned int b[]; unsigned int t; } pkt; int main(){ unsigned int* arr = (unsigned int*) malloc(sizeof(int) * 10); arr[0] = 0xa...
A C++ solution: #include <iostream> using namespace std; class Packet { public: Packet (int body_size) : m_body_size (body_size) { m_data = new int [m_body_size + 2]; } ~Packet () { delete [] m_data; m_data = 0; } int &Header () { return m_data [0]; } int &Trailer () { ...
1,257,640
1,257,657
Boost Program Options Examples
In the boost tutorials online for program options : http://www.boost.org/doc/libs/1_39_0/doc/html/program_options/tutorial.html#id2891824 It says that the complete code examples can be found at "BOOST_ROOT/libs/program_options/example" directory. I could not figure out where is this. Can anyone help me finding the exam...
On Debian systems, you find it in /usr/share/doc/libboost-doc/examples/libs/program_options. Otherwise, I suggest to download the archive from boost.org and have a look there.
1,257,643
1,257,654
Writing an app to interact with SQL 2008 without managed code
I want to write a winPE(vista) application that connects to a DB and just writes a row in a table saying it booted winPE. Here is my problem. I only ever do .NET. I'm pretty familiar with OO concepts so I'm finally taking the plunge to unmanaged code. I assume I have to use visual studio's unmanaged c++ project type, b...
Personally, I use OLEDB for all my old data access, its the underlying system that drives the others while still being cross-DB, so it might not be as easy to use as ADO, but once you get the concepts, create the classes to hold the data rows, its really simple. Here's some example code that should be useable almost as...
1,257,721
1,259,198
Can I use a mask to iterate files in a directory with Boost?
I want to iterate over all files in a directory matching something like somefiles*.txt. Does boost::filesystem have something built in to do that, or do I need a regex or something against each leaf()?
EDIT: As noted in the comments, the code below is valid for versions of boost::filesystem prior to v3. For v3, refer to the suggestions in the comments. boost::filesystem does not have wildcard search, you have to filter files yourself. This is a code sample extracting the content of a directory with a boost::filesyst...
1,257,744
1,257,760
Can I use break to exit multiple nested 'for' loops?
Is it possible to use the break function to exit several nested for loops? If so, how would you go about doing this? Can you also control how many loops the break exits?
AFAIK, C++ doesn't support naming loops, like Java and other languages do. You can use a goto, or create a flag value that you use. At the end of each loop check the flag value. If it is set to true, then you can break out of that iteration.
1,257,844
1,257,892
Getting mouse position unbounded by screen size, c++ & windows
I'm currently writing a c++ console application that grabs the mouse position at regular intervals and sends it to another visual application where it is used to drive some 3d graphics in real time. The visual app is closed source and cannot be altered outside it's limited plug-in functionality. Currently I'm using ...
I don't have any direct experience with raw input, which is probably what you need to tap into. According to MSDN, you have to register the device, then setup your winproc to accept the WM_INPUT messages and then do your calculations based on the raw data. Here's another relevant link.
1,258,051
3,389,144
0xDEADBEEF equivalent for 64-bit development?
For C++ development for 32-bit systems (be it Linux, Mac OS or Windows, PowerPC or x86) I have initialised pointers that would otherwise be undefined (e.g. they can not immediately get a proper value) like so: int *pInt = reinterpret_cast<int *>(0xDEADBEEF); (To save typing and being DRY the right-hand side would n...
Generally it doesn't matter exactly what pattern you write, it matters that you can identify the pattern in order to determine where problems are occurring. It just so happens that in the Linux kernel these are often chosen so that they can be trapped if the addresses are dereferenced. Have a look in the Linux kernel a...
1,258,055
1,258,071
Is it OK to use "delete this" to delete the current object?
I'm writing a linked list and I want a struct's destructor (a Node struct) to simply delete itself, and not have any side effects. I want my list's destructor to iteratively call the Node destructor on itself (storing the next node temporarily), like this: //my list class has first and last pointers //and my nodes each...
If the Node destructor is being called, then it's already in the process of being deleted. So a delete doesn't make sense inside your Node destructor. Also this is wrong: while (temp->next() != NULL) { delete temp; temp = temp->next(); } Instead you should get temp->next() into a temp variable. Otherwise ...
1,258,097
1,258,102
Best way to serialize a Float in java to be read by C++ app?
I need to serialize a java Float to be read by an application written in C++ over Socket comms. Is there a standard for this? It would be easiest to use the method floatToIntBits in the Float Class, however I am not sure how standard that is.
That is, in fact, pretty standard. The floatToIntBits function gives you the actual bytes of the IEEE encoding of the float. The only problem is that the bytes will be big-endian, so you'll have to reverse the byte order when reading into your C++ application. (unless your C++ platform is also big-endian!)
1,258,201
1,258,220
Will using goto cause memory leaks?
I have a program in which i need to break out of a large bunch of nested for loops. So far, the way most people have been telling me to do it is to use an ugly goto in my code. Now, if i create a bunch of local stack (i think that's what they are called, if not, i mean just regular variables without using the new comma...
No, you will not cause a memory leak. Using a goto is not "exiting loops improperly." It's just not generally recommended from a code-structure point-of-view. That aside, when you leave the loop, the local variables will go out of scope and be popped off of the stack (i.e. cleaned up) in the process.
1,258,238
1,258,641
Language integration
I may be the minority here, but it seems through my entire academic/professional career I've been taught varying languages. During this time, syntax and programming paradigms were the focus, but at no point were we taught about integrating systems written using varying languages and the proper way to make this decisio...
There are four different models that I can think of: Embed a dynamic language inside an app that is primarily written in a more "systems" language, like Lua, Python or Javascript embedded in a Java, C++ or C# app. This is used primarily for a scripting / customization component to the app. This will be accomplished by...
1,258,240
1,258,306
Logging exchange of messages by a process
I am currently having an OS which does support logging mechanisms like syslog. However, it is tedious when it comes to debug a process ie to find out what events or messages have a particular process exchanged with other processes in the system. Can any one suggest me a better mechanism to do the same ?
I would recommend wrapping your message passing mechanism with some sort of abstraction. Then you can place diagnostics in the message passing layer. I'd imagine that this is a design pattern of some sort. Create an abstraction that includes connectors between processes and messages sent across the connectors. If your ...
1,258,631
1,258,639
Locking files in windows
I am working on some legacy code which opens a file and adds binary data to the file: std::ifstream mInFile; #ifdef WINDOWS miWindowsFileHandle = _sopen(filename.c_str(), O_RDONLY , SH_DENYWR, S_IREAD); #endif mInFile.open(filename.c_str(), std::ios_base::binary); For some reason the code ope...
It opens twice because the first one opens it, and locks it. Then fstream opens it again (somewhat contradictory to the intent of the previous statement.) On how to just lock the file, check this question out.
1,258,633
1,258,667
How to programmatically (C/C++) get Country code on Linux?
I'm porting my application into Linux (from Windows). I have such code: char buffer[32] = {0}; if ( GetLocaleInfoA(LOCALE_USER_DEFAULT, LOCALE_ICOUNTRY, buffer, _countof(buffer)) ) { std::string newPrefix(buffer); if ( !newPrefix.empty() && ( newPrefix != "-1" ) ) { countryPrefix_ = newPrefix; ...
there is no OS Wide locale setting for Unix. There can be a default used for users which don't overwrite it, but most users do overwrite it. And it is quite common to leave it as "C". there is no standard C or C++ way to get the information you want. the posix way of getting information related to the locale is to s...
1,258,718
1,259,055
Hex to String Conversion C++/C/Qt?
I am interfacing with an external device which is sending data in hex format. It is of form > %abcdefg,+xxx.x,T,+yy.yy,T,+zz.zz,T,A*hhCRLF CR LF is carriage return line feed hh->checksum %abcdefg -> header Each character in above packet is sent as a hex representation (the xx,yy,abcd etc are replaced with actual nu...
If your 0x05 is converted to the char '\x05', then you're not having hexadecimal values (that only makes sense if you have numbers as strings anyway), but binary ones. In C and C++, a char is basically just another integer type with very little added magic. So if you have a 5 and assign this to a char, what you get is ...
1,259,056
1,259,088
overloaded "=" equality does not get called when making obj2 = obj1
i have this class called MemoryManager, it is supposed to implement a simple smart pointer, (count reference); i have a vector where i store the requested pointers,and i return the index of the pointer to the caller.. when a user creates a pointer of type MemoryManager he calls an initializer function called modified...
From you code, you have defined operator= for the MemoryManager class taking a void* . Your example code is initializing ClassA pointers and not assigning to MemoryManager instances. There are three reasons why your code is not being called. You are initializing not assigning, so if anything a constructor would be cal...
1,259,099
1,259,125
std::queue iteration
I need to iterate over std::queue. www.cplusplus.com says: By default, if no container class is specified for a particular queue class, the standard container class template deque is used. So can I somehow get to the queue's underlying deque and iterate over it?
If you need to iterate over a queue then you need something more than a queue. The point of the standard container adapters is to provide a minimal interface. If you need to do iteration as well, why not just use a deque (or list) instead?
1,259,192
1,259,466
webcam access in c++
I want to access the webcam so I can do some precessing on the images, like tracking a light, but I can't find a way to access the webcam. I googled it but I got confused. Can you point me to a library that can do that (windows)? and maybe also provide an example? I would need to periodically get a pixel map of the ima...
Checkout OpenCV. It is a cross-platform computer vision SDK and has modules to capture images from the webcam. Maybe too feature rich for you, but it's worth a look.
1,259,261
1,259,441
Where do I put ATL dlls so they will work
A colleague developed a IE Plugin which I require to run for a piece of work using ATL. I have all of the source code and the compiled dll as well as a regedit. I have run the reg edit and moved the dll to the C:\Windows\System32 directory where I thought it was supposed to reside but that doesn't appear to have worked...
I assume that you're talking about this IE plugin. You should register your DLL using regsvr32.exe. This will register the COM classes (add some entries in windows registry). The path where DLL was stored when registering is the one considered when instantiating the COM class. If the dll was previously registered in sy...
1,259,272
1,259,324
Is there a way to forward declare covariance?
Suppose I have these abstract classes Foo and Bar: class Foo; class Bar; class Foo { public: virtual Bar* bar() = 0; }; class Bar { public: virtual Foo* foo() = 0; }; Suppose further that I have the derived class ConcreteFoo and ConcreteBar. I want to covariantly refine the return type of the foo() and bar() met...
You can fake it quite easily, but you lose the static type checking. If you replace the dynamic_casts by static_casts, you have what the compiler is using internally, but you have no dynamic nor static type check: class Foo; class Bar; class Foo { public: Bar* bar(); protected: virtual Bar* doBar(); }; class Bar...
1,259,291
1,259,332
Check if service is running?
Possible Duplicate: Querying if a Windows Service is disabled (without using the Registry)? I need to check if 'Event Log' services in running or not. How to do that?
Use OpenSCManager(), then OpenService(), then ControlService().
1,259,638
1,259,678
In C++, when does a process retain allocated memory even though delete is called?
I would like to understand what is going on in the GCC runtime in the following situation. I have a C++ program that allocates many blocks of memory and then deletes them. What's puzzling is that the memory is not being returned to the OS by the GCC runtime. Instead, it is still being kept by my program, I assume in ca...
The memory allocator used by the C library allocates stuff in a variety of ways depending on how big the chunk is. Pages are not always returned to the OS when memory is freed, particularly if you do many small allocations. Memory can only be returned to the OS on a page-by-page basis, not for small allocations. If you...
1,259,719
1,259,747
Can I combine the regular expressions questions ([\\d]*$) and ([\\d]*)c$
I have two simple questions about regular expressions. Having the string $10/$50, I want to get the 50, which will always be at the end of the string. So I made: ([\\d]*$) Having the string 50c/70c I want to get the 70, which will always be at the end of the string(i want it without the c), so I made: ([\\d]*)c$ Both s...
(a) is easy: (\d+)c?$ (b) you can't do with regular expressions.
1,259,803
1,259,845
What does zero-sized array allocation do/mean?
Looking at some example code and come across some zero-size array allocation. I created the following code snippet to clarify my question This is valid code: class T { }; int main(void) { T * ptr = new T[0]; return 0; } What is its use? Is ptr valid? Is this construct portable?
5.3.4 in the C++ Standard: 6 Every constant-expression in a direct-new-declarator shall be an integral constant expression (5.19) and evaluate to a strictly positive value. The expression in a direct-new-declarator shall have integral or enumeration type (3.9.1) with a non-negative value... 7 When the value of the expr...
1,259,815
1,260,078
_beginthreadex static member function
How do I create a thread routine of a static member function class Blah { static void WINAPI Start(); }; // .. // ... // .... hThread = (HANDLE)_beginthreadex(NULL, 0, CBlah::Start, NULL, NULL, NULL); This gives me the following error: ***error C2664: '_beginthreadex' : cannot convert parameter 3 from 'void (vo...
Sometimes, it is useful to read the error you're getting. cannot convert parameter 3 from 'void (void)' to 'unsigned int (__stdcall *)(void *)' Let's look at what it says. For parameter three, you give it a function with the signature void(void), that is, a function which takes no arguments, and returns nothing. It fa...
1,259,834
1,260,798
Is there a difference between std::map<int, int> and std::map<const int, int>?
From what I understand, the key in a value pair in an std::map cannot be changed once inserted. Does this mean that creating a map with the key template argument as const has no effect? std::map<int, int> map1; std::map<const int, int> map2;
The answer to your title question is yes. There is a difference. You cannot pass a std::map<int, int> to a function that takes a std::map<const int, int>. However, the functional behavior of the maps is identical, even though they're different types. This is not unusual. In many contexts, int and long behave the same, ...
1,260,040
1,260,060
Casting between unrelated congruent classes
Suppose I have two classes with identical members from two different libraries: namespace A { struct Point3D { float x,y,z; }; } namespace B { struct Point3D { float x,y,z; }; } When I try cross-casting, it worked: A::Point3D pa = {3,4,5}; B::Point3D* pb = (B::Point3D*)&pa; cout << pb->x << " " << pb-...
If the structs you are using are just data and no inheritance is used I think it should always work. As long as they are POD it should be ok. http://en.wikipedia.org/wiki/Plain_old_data_structures According to the standard(1.8.5) "Unless it is a bit-field (9.6), a most derived object shall have a non-zero size and shall...
1,260,175
1,264,871
Building log4cxx on visual 2005
When I build the log4cxx on Visual 2005 according to instructions http://logging.apache.org/log4cxx/building/vstudio.html, I am getting error below; 1>------ Build started: Project: apr, Configuration: Debug Win32 ------ 1>Compiling... 1>userinfo.c 1>c:\program files\microsoft visual studio 8\vc\platformsdk\include\rpc...
I remember having a problem building log4cxx.0.10.0 in windows (I don't remember if it was the exactly the same one you have) and I followed this steps. I hope that helps.
1,260,244
1,260,429
What is the most simple/elegant way to calculate the length of a number written as text?
Given the maximum possible value, how to simply express the space needed to write such number in decimal form as text ? The real task: logging process ids (pid_t) with fixed length, using gcc on Linux. It'd be good to have a compile time expression to be used in the std::setw() iomanipulator. I have found that linux/th...
You could do it with a little template meta programming: //NunLength_interal does the actual calculation. template <unsigned num> struct NumLength_internal { enum { value = 1 + NumLength_internal<num/10>::value }; }; template <> struct NumLength_internal<0> { enum { value = 0 }; }; //NumLength is a wrapper to handle...
1,260,253
12,971,523
How do I put an QImage with transparency onto the clipboard for another application to use?
I have a QImage that I would like to put on the clipboard, which I can do just fine. However the transparency is lost when that data is pasted into a non-Qt application. The transparent part just comes out as black. I tried saving the data as a transparent PNG but nothing is usable on the clipboard. This is what I h...
I had the same problem. I replaced mimeData->setData("image/png", data); with mimeData->setData("PNG", data); It works in MS Office and Gimp, but not in OpenOffice.
1,260,510
1,260,524
Why can I not initialize an array by passing a pointer to a function?
I know this has a really simple explanation, but I've been spoiled by not having to use pointers for a while. Why can't I do something like this in c++ int* b; foo(b); and initialize the array through... void Something::foo(int* a) { a = new int[4]; } after calling foo(b), b is still null. why is this?
Pointers are passed to the function by value. Essentially, this means that the pointer value (but not the pointee!) is copied. What you modify is only the copy of the original pointer. There are two solutions, both using an additional layer of indirection: Either you use a reference: void f(int*& a) { a = new int[...
1,260,775
1,260,852
Usage guidelines: shared versus normal pointers
Is there a rigid guideline as to when one should preferably use boost::shared_ptr over normal pointer(T*) and vice-versa?
My general rule is, when memory gets passed around a lot and it's difficult to say what owns that memory, shared pointers should be used. (Note that this may also indicate a poor design, so think about things before you just go to shared pointers.) If you're using shared pointers in one place, you should try to use the...
1,260,954
1,261,168
How can I keep track of (enumerate) all classes that implement an interface
I have a situation where I have an interface that defines how a certain class behaves in order to fill a certain role in my program, but at this point in time I'm not 100% sure how many classes I will write to fill that role. However, at the same time, I know that I want the user to be able to select, from a GUI combo/...
Create a singleton where you can register your classes with a pointer to a creator function. In the cpp files of the concrete classes you register each class. Something like this: class Interface; typedef boost::function<Interface* ()> Creator; class InterfaceRegistration { typedef map<string, Creator> CreatorMap...
1,261,027
1,261,044
C++ unit testing with Microsoft MFC
I'm trying to convince my organization to start running unit tests on our C++ code. This is a two-part question: Any tips on convincing my employer that unit testing saves money in the long run? (They have a hard time justifying the immediate expenses.) I'm not familiar with any C++ testing frameworks that integrate w...
I can answer the second question - the Boost Test framework can be used with MFC and someone has posted an excellent article about it on Code Project: http://www.codeproject.com/KB/architecture/Designing_Robust_Objects.aspx
1,261,198
1,261,287
Automatic break when contents of a memory location changes or is read
The old DEC Tru64 UNIX debugger had a feature (called "watchpoints to monitor variables") that would watch a memory location (or range of addresses) for read or write activity and when it detected such activity would break the program so you could investigate why. See for details: http://h30097.www3.hp.com/docs/base_d...
Yeah, you can do this in visual studio. You can create a "New Data Breakpoint" under the debug menu while you're broken in a running program. You then specify the address to watch and the number of bytes. This only works for changing the value. I don't know how to watch for read access. However it's a very common quest...
1,261,264
1,278,998
example for using streamhtmlparser
Can anyone give me an example on how to use http://code.google.com/p/streamhtmlparser to parse out all the A tag href's from an html document? (either C++ code or python code is ok, but I would prefer an example using the python bindings) I can see how it works in the python tests, but they expect special tokens alread...
import py_streamhtmlparser parser = py_streamhtmlparser.HtmlParser() html = """<html><body><a href='http://google.com' id=100> link</a><p><a href=heise.de/></body></html>""" cur_attr = cur_value = None for index, character in enumerate(html): parser.Parse(character) if parser.State() == py_streamhtmlparse...
1,261,380
1,261,428
What's the simplest and most efficient data structure for building acyclic dependencies?
I'm trying to build a sequence that determines the order to destroy objects. We can assume there are no cycles. If an object A uses an object B during its (A's) construction, then object B should still be available during object A's destruction. Thus the desired order of destruction is A, B. If another object C uses ob...
Since dependencies are always initialised before the objects that depend on them, and remain available until after such objects are destroyed, it should always be safe to destroy objects in strictly reverse order of initialisation. So all you need is a linked list to which you prepend objects as they are initialised an...
1,261,558
1,263,604
Is there a generally accepted idiom for indicating C++ code can throw exceptions?
I have seen problems when using C++ code that, unexpectedly to the caller, throws an exception. It's not always possible or practical to read every line of a module that you are using to see if it throws exceptions and if so, what type of exception. Are there established idioms or "best practices" that exist for dealin...
The idiomatic way to solve the problem is not to indicate that your code can throw exceptions, but to implement exception safety in your objects. The standard defines several exception guarantees objects should implement: No-throw guarantee: The function will never throw an exception Strong exception safety guarantee:...
1,261,566
1,276,941
Converting old and new local times to UTC under Windows XP/Server 2003
My application converts past and present dates from local time to UTC. I need to ensure I will honor any future DST updates to Windows while still correctly handling past dates. The application is written in C++ and is running on Server 2003. Options I've researched: gmtime() and localtime() are not always correct for...
I think I'd prefer to re-implement GetTimeZoneInformationForYear and possibly GetDynamicTimeZoneInformation based on the information in the registry at HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones. That way, your code will follow Windows updates and you can swap the dirty code out for the ...
1,261,598
1,261,623
A generic method to set the length of a dynamic array of arbitrary type in c++
I am doing a project converting some Pascal (Delphi) code to C++ and would like to write a function that is roughly equivalent to the Pascal "SetLength" method. This takes a reference to a dynamic array, as well as a length and allocates the memory and returns the reference. In C++ I was thinking of something along th...
Use std::vector instead of raw arrays. Then you can simply call its resize() member method. And make the function a template to handle arbitrary types: If you want to use your function, it could look something like this: template <typename T> std::vector<T>& setlength(std::vector<T>& v, int new_size) { v.resize(n...
1,261,680
1,261,778
Code crash when storing objects in `std::map`
typedef std::map<int, MyObject*> MyMap; MyMap* myMap = new MyMap; // ... myMap->insert( MyMap::value_type( 0, objectOfType_MyObject ) ); Why does my code crash with a stack trace going down to std::less<int>::operator() ? I understand that if I use a custom key class that I must provide a comparator, but this ...
This code works (compiles & runs) for me: #include <map> class MyObject { }; int main(void) { typedef std::map<int, MyObject*> MyMap; MyMap *myMap = new MyMap; MyObject *obj = new MyObject; myMap->insert(MyMap::value_type(0, obj)); delete obj; delete myMap; } So the problem lies in the det...
1,262,063
1,262,077
Preprocessor macro expansion to another preprocessor directive
Initially I thought I needed this, but I eventually avoided it. However, my curiosity (and appetite for knowledge, hum) make me ask: Can a preprocessor macro, for instance in #include "MyClass.h" INSTANTIATE_FOO_TEMPLATE_CLASS(MyClass) expand to another include, like in #include "MyClass.h" #include "FooTemplate.h" ...
I believe that cannot be done, this is because the pre-processor is single pass. So it cannot emit other preprocessor directives. Specifically, from the C99 Standard (6.10.3.4 paragraph 3): 3 The resulting completely macro-replaced preprocessing token sequence is not processed as a preprocessing directive even i...
1,262,076
1,272,704
ActiveMQ c++ tutorial
Can anyone recommend a good tutorial on JMS with c++ and ActiveMQ?
The examples that ship with the library are also pretty good. They have simple, straightforward examples like a simple async consumer and a simple producer which work together. http://svn.apache.org/viewvc/activemq/activemq-cpp/trunk/activemq-cpp/src/examples/
1,262,081
1,262,676
How to encrypt and decrypt a file with Qt/C++?
I want to create a program, which can encrypt and decrypt a complete file with an individual password. Is there any way to manage this in Qt and/or C++ and how?
I've never used it myself, but I've heard great things about QCA. It's cross platfrom, uses a Qt-style API and Qt datatypes.
1,262,308
1,263,313
Read binary C float in Actionscript 3?
I have binary C/C++ data types (e.g. in memory version of a C float) which I need to read into Actionscript 3 and would prefer not to code this from scratch. Anyone know of any libraries, sample code, pseudo code to help with this? For example: C/C++ app: float f = 1.1; SaveFloatToFile(f, 'myfile.bin'); Actionscript 3...
I did some more digging around and discovered that ByteArray has most of what I need (possibly with some bit shifting beforehand)