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
2,990,760
2,990,924
Is assignment of braced-init-list to an array correct?
The standard says, under 5.17/9 A braced-init-list may appear on the right-hand side of - an assignment to a scalar [...] - an assignment defined by a user-defined assignment operator [..] While in GCC 4.5.1-pre9999, I can compile this (using -std=c++0x, NOT -std=gnu++0x) #include <iostream> int main() {...
It looks like a bug to me. The initialization (int test = {1,2,3};) is fine, but as far as I can see, nothing in the standard allows the assignment.
2,990,852
3,027,037
How the NPP_NewStream of NPAPI wall called? Automatically or by a plugin-request?
I have read a lots document on NPAPI but I still do not understand: How the NPP_NewStream of NPAPI wall called? Automatically by Browser, whenever it load a page, an image, an video,.... or manually by our plugin-request ?
It can be called as a result of both: automically for e.g. src attributes or for full-page plugin-instances by plugin-request as a result of e.g. calling NPN_GetURL()
2,990,881
2,990,919
C++ - Where to throw exception?
I have some kind of an ideological question, so: Suppose I have some templated function template <typename Stream> void Foo(Stream& stream, Object& object) { ... } which does something with this object and the stream (for example, serializes that object to the stream or something like that). Let's say I also add some ...
In this case it's better to throw it in the lower-level Foo function so that you don't have to copy the validation and exception throwing code in all of your wrappers. In general using exceptions correctly can make your code a lot cleaner by removing a lot of data validation checking that you might otherwise do redund...
2,990,903
2,990,942
Best XML Library in C++, Fast Set-Up
I was wondering what is the best XML Library in C++ (I'm using Visual Studio), considering fast set-up is critical. Basically, I want to create a file to save annotations on various .avi files. Thank you in advance.
You should be able to get TinyXML set up and working in a matter of minutes.
2,990,954
2,991,009
Mixing libraries with and without RTTI with GCC on Mac OS X?
I've been banging my head on an issue and before I continue injuring myself some more, I'd like to confirm: Is it possible to have a GCC project that uses libraries that are compiled with and without RTTI? So, for example, I have project A (compiled without RTTI) that uses library B (compiled with RTTI) and library C...
Presumably the binaries were built with (or without) the -fno-rtti switch? If so, I can't see any reason why this should not work - RTTI is only provided for classes with virtual functions in any case, so there is no major change in binary format or anything like that. Are you experiencing any specific problems?
2,991,085
2,992,744
Quantization Matrices in x264
I've downloaded the source code and am wading through it --- does anybody know where the QMs for the images and the residuals are stored?
As of x264 snapshot 20100603-2245/, they're stored in: common/set.h
2,991,153
2,991,260
Newbie: Minimal program to display a PNG in a window
All, I must have a fundamental neuron missing, but I cannot get a simple program to load a PNG file and display it in a window. I'm not sure if it is a QPixmap, a QPicture, or what. All of the samples in the QTCreator are a bit more than I need right now. Baby steps... I can get the window to display, and the program...
this example is minimal: http://doc.trolltech.com/4.6/widgets-imageviewer.html You will want to have a look at the function ImageViewer::open(): Build a QImage object from a filename; Convert your QImage to a QPixmap with QPixmap::fromImage(); Put your QPixmap in a QLabel with QLabel::setPixmap(). The QImage object w...
2,991,225
2,991,257
Magic++ RGB colors values
Does anyone know why is Magic++ giving me RGB values less than 1?
The maximum RGB component value in Magick is 1 and the minimum is 0. So the values should be between 0 and 1. For example, RGB values of (0.5, 0.5, 0.5) represents a grey, (1.0, 0, 0) would be a pure red, etc. Check out the documentation. You may also find this of interest, it discusses what typically happens when the ...
2,991,344
2,991,394
Logical Programming Problem
I've been trying to solve this problem for quite sometime but I am having trouble with it. Let's say on a trigger, you receive values. First trigger: You get 1 Second trigger: You get 1, 2 Third trigger: You get 1, 2, 3 So, I store 1. For 2nd trigger, I store 2 since 1 already exist. For 3rd trigger, I store 3 since ...
Use a std::set<int> container. When a trigger arrives, clear it an insert all the values from trigger. This should be ok if you work with just a few numbers (about ten or so). With more, a little bit more sophisticated approach might be required.
2,991,406
2,991,445
Windows C++: LPCTSTR vs const TCHAR
In my application i'm declaring a string variable near the top of my code to define the name of my window class which I use in my calls to RegisterClassEx, CreateWindowEx etc.. Now, I know that an LPCTSTR is a typedef and will eventually follow down to a TCHAR (well a CHAR or WCHAR depending on whether UNICODE is defin...
The two declarations are not identical. The first creates a pointer, the second an array of TCHAR. The difference might not be apparent, because an array will decompose into a pointer if you try to use it, but you'll notice it instantly if you try to put them into a structure for example. The equivalent declaration to ...
2,991,521
2,991,559
C++: Can't use std::wstringstream
For some reason, my project won't compile when I try to create a wstringstream: std::wstringstream stringstream; This causes error C2079: 'stringstream' uses undefined class 'std::basic_stringstream<_Elem, _Traits, _Alloc> with [_Elem=wchar_t, _Traits=std::char_traits, _Alloc=std::allocator' What am I doing wron...
Include <sstream> header
2,991,680
4,415,024
troubles with boost::asio::io_service::poll()
the following code: /***************************************************************************/ boost::mutex m; struct func { func(int v):n(v) {} void operator()() { { boost::mutex::scoped_lock l(m); std::cout << "run function " << n << std::endl; } for ( int idx = 0; idx < 4; ++id...
This is an old question but you never really got an answer about run vs poll. io_service::run will keep running as long as there is something to do, such as waiting on a deadline timer or IO completion notification, etc. This is why there is the work object to keep run from exiting. io_service::poll will only execute...
2,991,740
2,991,789
C++: Get LPCWSTR from wstringstream?
If I have a wstringstream, and I want to get its .str() data as a LPCWSTR, how can I do that?
You can do wstringstream.str().c_str() as DeadMG writes. However, the result of that call is only valid until the end of lifetime of the expression, this is part of. Specifically, this const LPCWSTR p = wss.str().c_str(); f(p); // kaboom! will not work, because wstringstream.str() returns a temporary object and .c_s...
2,991,753
2,991,797
Refactoring a "dumb" function into generic STL-style with iterators to containers
I've managed to wrap my head around some of C++'s functional capacities (for_each, mapping functions, using iterators...) but the construction of the templates and function argument lists for taking in generic containers and iterators still eludes me. I have a practical example I'm hoping someone can illustrate for me:...
You could use std::transform and std::plus: std::transform(iteration_data.begin(), iteration_data.end(), running_total.begin(), iteration_data.begin(), std::plus<int>()); And in your function, that would be: template <typename Iter1, typename Iter2> void UpdateRunningTotal(Iter1 pBegin, Iter1 pEnd, Ite...
2,991,828
2,991,850
Boost in Visual Studio 2010, IntelliSense error
I would like to see if you could orient me. It happens that I compiled and referenced the boost libraries in order to use them with Visual Studio 2010. When building my test project I get these two IntelliSense errors 1 IntelliSense: #error directive: "Macro BOOST_LIB_NAME not set (internal error)" c:\boost_1_43_0\bo...
The Visual Studio IntelliSense error checking for C++ is not perfect and often reports errors that aren't really errors (those are links to three false positives that I've found and reported; they aren't related to your problem, though).
2,991,837
2,991,859
Hello world/Console Project in Visual Studio 2008 64 bit
So I am trying to run console 64 bit Hello World program. I have Windows 7 Enterprise x64 bit version. I have installed Visual Studio 2008 and have added all of components needed for 64 bit. I want to create simple console application. It turns out to be a problem. I have simple standard hello world project. I have cre...
Instead of starting with an Empty Project, choose a project of type "Console Application" in Visual Studio.
2,991,867
2,991,880
Is there an alternative to Pidgin, but with less restrictive licensing?
Recently came across pidgin. Its great, and does what I want, but I am not too keen on the GPL license. Other any alternatives, with less restrictive licenses? I would prefer the library to be C or C++, as I am most familiar with those languages, but a an IM library implemented in python would be interesting too.
Take a look at kde's kopete. The chat client itself is still GPL but it's underlying library libkopete is LGPL. So you could link with it pretty freely.
2,991,927
2,993,476
How to force inclusion of an object file in a static library when linking into executable?
I have a C++ project that due to its directory structure is set up as a static library A, which is linked into shared library B, which is linked into executable C. (This is a cross-platform project using CMake, so on Windows we get A.lib, B.dll, and C.exe, and on Linux we get libA.a, libB.so, and C.) Library A has an...
It turns out my original attempt was mostly there. The following works: extern "C" void Af(void); void (*Af_fp)(void) = &Af; For those that want a self-contained preprocessor macro to encapsulate this: #if defined(_WIN32) # if defined(_WIN64) # define FORCE_UNDEFINED_SYMBOL(x) __pragma(comment (linker, "/export:" #x...
2,991,957
2,992,245
Impersonate SYSTEM (or equivalent) from Administrator Account
This question is a follow up and continuation of this question about a Privilege problem I'm dealing with currently. Problem Summary: I'm running a program under a Domain Administrator account that does not have Debug programs (SeDebugPrivilege) privilege, but I need it on the local machine. Klugey Solution: The prog...
By design, no process is allowed to achieve NT AUTHORITY\SYSTEM rights, unless it is started by another process with NT AUTHORITY\SYSTEM rights. The service is a workaround because the Service Control Manager itself is started by the Kernel at system start. Unfortunately, the operating system is designed to prevent exa...
2,992,066
2,994,344
Code to strip diacritical marks using ICU
Can somebody please provide some sample code to strip diacritical marks (i.e., replace characters having accents, umlauts, etc., with their unaccented, unumlauted, etc., character equivalents, e.g., every accented é would become a plain ASCII e) from a UnicodeString using the ICU library in C++? E.g.: UnicodeString st...
After more searching elsewhere: UErrorCode status = U_ZERO_ERROR; UnicodeString result; // 's16' is the UTF-16 string to have diacritics removed Normalizer::normalize( s16, UNORM_NFKD, 0, result, status ); if ( U_FAILURE( status ) ) // complain // code to convert UTF-16 's16' to UTF-8 std::string 's8' elided strin...
2,992,141
2,992,161
C++ enum casting and templates
I get the following error with VS2008: Conversion to enumeration type requires an explicit cast (static_cast, C-style cast or function-style cast) When casting a down casting a ClassA to ClassA_1 and ClassA_1 is a templated class that received an enum for parameter such as: THIS IS AN EDIT OF MY QUESTION WHICH RE-USE A...
There are so many syntax errors here, I don’t know where to begin. Next time, please post the actual code you used. For starters, I’m assuming that you meant to write this: ClassA<myenum>* a = new ClassA_1<myenum>(); In other words, a is a pointer and its type is ClassA<myenum>*, not merely ClassA (and we’ll ignore th...
2,992,144
3,007,043
Making a window a desktop in XLib/Qt
I am trying to write a simple program to act as my desktop background in Qt, I have made it all work fine apart from making it a Desktop Widget. I have no idea on how to do this, I don't mind using XLib or Qt for doing this, but if anyone has some suggestions I would be very happy.
I have created a simple example that will fill the desktop background white. It is easy to make it draw an image. class DesktopWidget : public QWidget { Q_OBJECT public: DesktopWidget() { setAttribute(Qt::WA_X11NetWmWindowTypeDesktop); resize(QApplication::desktop()...
2,992,237
2,992,270
C++ Dynamic Allocation Mismatch: Is this problematic?
I have been assigned to work on some legacy C++ code in MFC. One of the things I am finding all over the place are allocations like the following: struct Point { float x,y,z; }; ... void someFunc( void ) { int numPoints = ...; Point* pArray = (Point*)new BYTE[ numPoints * sizeof(Point) ]; ... //do some...
Formally the code causes undefined behavior because of the pointer type mismatch in new[]/delete[]. In practice it should work fine. The pointer type mismatch issue can easily be fixed by adding a cast to the delete-expression delete [] (BYTE *) pArray; If Point type is defined as shown in the question (i.e. with triv...
2,992,483
2,992,608
Keeping a window always on top -- including menus (win32)
I would like to have a layered window that is always-on-top, which I can accomplish, but there are certain screen elements that still get drawn over it, such as menus (including the start menu). Is there any way to make a window or child window of my application have a high enough top-ness property that it will draw o...
There's only one level of TopMost, you'll compete with any other program that insists on being top-most. Try osk.exe for example. I'm guessing it uses a WH_SHELL hook to win.
2,992,512
2,992,572
How to display scrollbar for a list view whose contents keep changing?
I have a ListView-like control that displays a list of items of various heights. The contents of the list, and the heights of the items can change – a background thread is populating the list and calculating the layout of each item, possibly even while the user is scrolling the content. Which brings me to my question:...
IMO the fundamental problem with a classic scrollbar is that due to background population, the valid range is changing - and thus, the meaning of a scrollbar position changes. If you can predict the full range of items, you can still provide a scrollbar and replace yet-unknown items with "loading...". Otherwise, a roc...
2,992,688
2,993,486
how do I set up an SMS server?
Just like google as the number GOOGL (46645), I would like to also set up a server like this that will have the ability to receive text messages.
While Twilio doesn't yet support shortcodes, you can be up and running accepting text messages using simple POST requests sent to your server very quickly. There are other similar services out there as well so look around and use the one you like the most. [Full disclosure: I work for Twilio]
2,992,752
2,993,981
How do I get the number of visible characters from a UTF-8 encoded char*?
I have a UTF-8 encoded char*. Is there a standard function to calculate the number of visible characters represented by the byte array? I'm on Red Hat (RHEL 5).
Check the iconv library: man iconv_open. One can convert the utf-8 string into say UCS-2 or UCS-4 where characters are of the same size. iconv is also (relatively) portable and not Linux or GNU specific. If Glib, suggested before, is available to you (beware: it is GPLed) then use it as it is a better way.
2,992,850
2,992,937
Get image data for Direct3d rendering stream
I would like to get at the raw image data, as in a pointed to a byte array or something like that, of the image output from a direct3d app without actually rendering it to the monitor. I need to do this so that I can render direct3d as a directshow source filter Visual studio 2008 c++
Create a surface to which you're going to render as an instance of IDirect3DSurface9. Set it as the target for your rendering with IDirect3DDevice9::SetRenderTarget.
2,992,894
2,992,974
program crashes at CIN input | C++
so i made a DOS program however my game always crashes on my second time running to the cin function. #include <iostream> #include <string> #include <ctime> #include <cstdlib> using namespace std; //call functions int create_enemyHP (int a); int create_enemyAtk (int a); int find_Enemy(int a); int create_enemyDef (in...
If your c_action variable is only intended to be a char, I'd suggest to use a char variable, rather than a string. You might want to try this way, and if you're still faced with an error, you might give scanf("%c", &c_action); //assuming you used a char.
2,992,948
2,992,956
Static Class Data Members and Constructors
How do I access a static member in a class with all static methods? I want to have a group of related functions but also have some important data members initialized before any of these functions are called. I thought a class with only static members would be the way to go. Compiler in VS2008 doesn't like me trying to ...
You need to define your static data member outside of the function, like class IPAddressResolver { private: static int a; IPAddressResolver(); public: static void TestMethod(); }; int IPAddressResolver::a = 0; void IPAddressResolver::TestMethod() { cout << "testMethod" << endl; } Your constructor is ...
2,993,020
2,993,054
Providing *implicit* conversion operator for template specialization
I have a templated sparse_vector<T> class, and I am also using Boost UBLAS. How would I provide implicit conversions between sparse_vector<double> and boost::numeric::ublas::compressed_vector<double>? I would also like to provide similar conversions between std::vector<double> and boost::numeric::ublas::vector<double>...
I'd assume that there's an iterator constructor for these types. If that assumption is accurate then it would be as simple as writing something like so: template < typename OutputVector, typename InputVector > OutputVector vector_cast(InputVector const& input) { return OutputVector(input.begin(), input.end()); } U...
2,993,094
2,993,125
multiple calls to realloc() seems to cause a heap corruption
What's the problem with this code? It crashes every time. One time it's a failed assertion "_ASSERTE(_CrtIsValidHeapPointer(pUserData));", other times it is just a "heap corrpuption" error. Changing the buffer size affects this issue in some strange ways - sometimes it crashes on the "realloc", and other times on the "...
You're trashing the heap. realloc can freely choose to return you memory from an entirely different location as it reallocates, and this is invalidating your ptr. Set ptr after reallocating.
2,993,103
2,993,177
How to use Unicode (UTF-8) in C++
Possible Duplicate: Unicode in C++ If I remembered correctly, the default character and string encoding in C++ are ASCII. Is there a simple way to enable Unicode support?
Current C++ doesn't specify encoding in any way. You might look into an actual Unicode library like ICU or, on some architectures and implementations you can use wchar_t to manipulate and hold Unicode strings. Edit: This answer was referring to C++03. As noted, it doesn't apply any longer.
2,993,304
3,016,501
How can I access the QUndoStack of a QTextDocument?
How can I access the QUndoStack of a QTextDocument? (For example, I want to be able to add custom QUndoCommand objects to the document's undo stack)
I have been reading the documentation and it doesn't seems to be a way to get the QUndoStack directly for the Widget. Probably the only way is to create your own QUndoStack object and manually add the changes and then re-implement the redo() / undo() slots. I would have a look to the source code, you can probably get ...
2,993,319
2,993,718
How to link Delphi with C++?
cpp.cpp extern "C" char* GetText() { return "Hello, world!"; } delphi.dpr {$APPTYPE CONSOLE} {$LINK 'cpp.obj'} function _GetText: PChar; cdecl; external; begin WriteLn(_GetText); end. I can't get this to work, no matter what I try. I tried various calling conventions, playing with underscores. even creating a ....
You have run into a limitation of the compiler. These two articles cover your options in fairly good detail: http://www.rvelthuis.de/articles/articles-cobjs.html http://www.rvelthuis.de/articles/articles-cppobjs.html
2,993,330
2,993,349
Can a lambda expression be passed as function pointer?
I am trying to pass a lambda expression to a function that takes a function pointer, is this even possible? Here is some sample code, I'm using VS2010: #include <iostream> using namespace std; void func(int i){cout << "I'V BEEN CALLED: " << i <<endl;} void fptrfunc(void (*fptr)(int i), int j){fptr(j);} int main(){ ...
In VC10 RTM, no - but after the lambda feature in VC10 was finalized, the standard committee did add language which allows stateless lambdas to degrade to function pointers. So in the future this will be possible.
2,993,339
2,993,356
C++ pointers on example
I have a sample code : #include <iostream> #include <conio.h> using namespace std; int main () { int firstvalue = 5, secondvalue = 15; int * p1, * p2; p1 = &firstvalue; p2 = &secondvalue; cout << "1.p1: " << p1 << ", p2: " << p2 << endl; cout << "1.*p1: " << *p1 << ", *p2: " << *p2 << endl; *p1 = 10;...
You just say: "Now p1 should point at the same memory block as p2 does". So they start pointing at the same memory block (to the same address) and, hence, share the same values.
2,993,393
2,993,422
Python - how to check if weak reference is still available
I am passing some weakrefs from Python into C++ class, but C++ destructors are actively trying to access the ref when the real object is already dead, obviously it crashes... Is there any Python C/API approach to find out if Python reference is still alive or any other known workaround for this ? Thanks
If you call PyWeakref_GetObject on the weak reference it should return either Py_None or NULL, I forget which. But you should check if it's returning one of those and that will tell you that the referenced object is no longer alive.
2,993,429
2,993,483
tchar safe functions -- count parameter for UTF-8 constants
I'm porting a library from char to TCHAR. the count parameter of this fragment, according to MSDN, is the number of multibyte characters, not the number of bytes. so, did I get this right? My project properties in VC9 say 'use unicode character set' and I think that's correct, but I'm not how that impacts my count para...
Yes, you get it right. The question, however, is why do you port it to TCHAR - something that is sensitive to _UNICODE define. Why not use UTF8 and char*?
2,993,513
2,993,530
How am i overriding this C++ inherited member function without the virtual keyword being used?
I have a small program to demonstrate simple inheritance. I am defining a Dog class which is derived from Mammal. Both classes share a simple member function called ToString(). How is Dog overriding the implementation in the Mammal class, when i'm not using the virtual keyword? (Do i even need to use the virtual keywor...
It's not overriding the ToString method in the base class as the base class method is not virtual. It is simply hiding that function with a function with an identical signature. When you call ToString() on a Dog object the Dog::ToString method is called. Why would it call any other ToString() method; the Dog:: declarat...
2,993,643
2,995,451
Figure out texture coordinate from 4 others?
Lets say I have 4 verticies and their texture coordinates. How could I then figure out the texture coords of a 5th vertex? Thanks say I have: v1 = (0,0) tex coord(1,0) v2.... v3... v4... v5 = (15,15) tex coord = ?? yea linear interpolation I suppose, To figure out the coords I do: vec.x / polywidth; vec.y / polyheight...
texture mapping is about mapping a 2d space to your 3d model. There is no generic way to extrapolate texture coordinates, because those completely depend on how you want to map your texture to your surface. More to the point, there are many possible texture coordinates, that will map a different part of your texture to...
2,993,658
2,993,744
Creating simple calculator with bison & flex in C++ (not C)
I would like to create simple C++ calculator using bison and flex. Please note I'm new to the creating parsers. I already found few examples in bison/flex but they were all written in C. My goal is to create C++ code, where classes would contain nodes of values, operations, funcs - to create AST (evaluation would be do...
http://www.progtools.org/compilers/tutorials/cxx_and_bison/cxx_and_bison.html is a mini-tutorial which should create something like what you want.
2,993,674
2,993,806
Need help with events in COM in pure C++!
guys! Very important question: Please, look at my project (300Kb). I can`t use MFC/ATL, pure C++ only. I have COM library (niapi.dll), but no sources/headers available, dll only. There is class for connecting to server (NiApi::SrvrSession), class has login event handler (NiApi::SrvrSession::OnLogin). I used #import "Ni...
COM events are handled via connection points. You need to write your own COM object that implements whichever event interface you are interested in. Then you need to connect it to the COM object that fires the events. First you QI the COM object for its IConnectionPointContainer, then find the corresponding connecti...
2,993,680
2,993,698
Is there any crossplatform C/C++ lib for files searching? (on hard drive)
Is there any crossplatform C\C++ lib for files searching? (on hard drive) What I need is simple - be able to find all images on users computer in all folders and subfolders with sise >= 200kb. How to do such thing? Can any one help me? Please.
Boost.Filesystem is a great library. Here is a code I wrote while ago, you can change the search criteria easily once you know the library(you can query the size and the extension): #include <iostream> #include <string> #include <vector> #include <boost/filesystem.hpp> using namespace std; using namespace boost::files...
2,993,712
2,993,727
Sort std::vector by an element inside?
I currently have a std::vector which holds std::vector of double. I'd want to sort it by the second element of the double vectore. ex: instead of sorting by MyVec[0] or myvec[1] I wat it to sort myVec[0] and myvec[1] based on myvec[0][1] myvec[1][1]. Basically sort by a contained value, not the objects in it. so if myv...
Just write the comparator: bool my_comparator(const std::vector<double>& lhs, const std::vector<double>& rhs) { assert(lhs.size() >= 2 && rhs.size() >= 2); return lhs[1] < rhs[1]; } ... std::sort(big_vector.begin(), big_vector.end(), my_comparator); It is better to write a functor instead of a function, but the co...
2,993,914
2,993,927
Safe placement new & explicit destructor call
This is an example of my codes: template <typename T> struct MyStruct { T object; } template <typename T> class MyClass { MyStruct<T>* structPool; size_t structCount; MyClass(size_t count) { this->structCount = count; this->structPool = new MyStruct<T>[count]; for( size_t i=0 ...
No, because both your constructor and destructor are invoked twice. Because you have this: template <typename T> struct MyStruct { T object; } When you construct a MyStruct<T> the compile will construct the inner T and when you delete the object the inner T will have the destructor called automatically. For this ...
2,994,005
2,994,066
Including external C++ libraries in version control
Possible Duplicate: Storing third-party libraries in source control I'm currently starting a project which is going to be developed on a few different computer and I'm keeping in sync with bzr. In the project I'm using a couple of 3rd party libraries, like SDL. In the past I've just pushed a copy of the compiled lib...
Use git subprojects, and either reference from the 3rd party library's main git repository, or (if it doesn't have one) create a new git repository for each required library. There's nothing reason why you're limited to just one git repository, and I don't recommend you use somebody else's project as merely a directory...
2,994,073
2,994,079
why there is no find for vector in C++
what's the alternative? Should I write by myself?
There is the std::find() algorithm, which performs a linear search over an iterator range, e.g., std::vector<int> v; // Finds the first element in the vector that has the value 42: // If there is no such value, it == v.end() std::vector<int>::const_iterator it = std::find(v.begin(), v.end(), 42); If your vector is so...
2,994,145
2,994,152
Why is it that an int in C++ that isnt initialized (then used) doesn't return an error?
I am new to C++ (just starting). I come from a Java background and I was trying out the following piece of code that would sum the numbers between 1 and 10 (inclusive) and then print out the sum: /* * File: main.cpp * Author: omarestrella * * Created on June 7, 2010, 8:02 PM */ #include <cstdlib> #include <ios...
Because it's not part of the C++ standard. The variable will just take whatever value is currently sitting in the memory it's assigned. This saves operations which can sometimes be unnecessary because the variable will be assigned a value later. It's interesting to note and very important for Java/.Net programmers to n...
2,994,533
2,994,552
How do you make cin typesafe?
It is well known that cin is not typesafe (e.g. cin >> integer; and entering "fifty five" will cause it to flip out). I have seen many not-so-elegant ways to hand this, such as getlining a string and using sstream to convert it to a number, or looping with cin.fail() and clearing the stream and reentering it, etc. Is t...
e.g. cin >> integer; and entering "fifty five" will cause it to flip out No, this will not cause it to "flip out;" it will cause the fail state of the stream to be set, just like with any other stream. This doesn't mean that std::cin is not type-safe. One option for handling errors reading from a stream would be to ...
2,994,596
2,994,602
Any side effect of not using USES_CONVERSION
Recently I made a utilities function like: // T2CA #include "ATLCONV.H" std::string Utils::CString2String(const CString& cString) { #if _MSC_VER > 1200 // Convert a TCHAR string to a LPCSTR // construct a std::string using the LPCSTR input CT2CA tmp(cString); std::string strStd (tmp); #else // Dep...
In ATL 7.0 USES_CONVERSION is not required anymore. Before that you needed to specify the USES_CONVERSION macro or else you'd get compile errors.
2,994,925
2,994,940
template function error
I have function which takes in an parameter of a class called "Triple", and am returning the averge of 3 values of type float. template <typename ElemT> float average(Triple ElemT<float> &arg){ float pos1 = arg.getElem(1); float pos2 = arg.getElem(2); float pos3 = arg.getElem(3); return ( (pos1+pos2+po...
The declaration of the function parameter uses wrong syntax. Maybe you meant to write this: template <typename ElemT> float average(Triple<ElemT> &arg){ ... } Or, if the function should just be specific to Triples of floats: float average(Triple<float> &arg){ ... }
2,994,965
2,995,218
C++ rvalue temporaries in template
Can you please explain me the difference between mechanism of the following: int function(); template<class T> void function2(T&); void main() { function2(function()); // compiler error, instantiated as int & const int& v = function(); function2(v); // okay, instantiated as const int& } is my reasoning ...
Because function returns a non-const value. Only objects can be const, because they store some state that could be modified if it weren't const. What you return there is not an object, but a pure value. Conceptually, they are not modifiable (like enumeration constants, for example), but they are not const qualified (li...
2,995,099
2,995,112
Malloc and constructors
Unlike new and delete operators malloc does not call the constructor when an object is created. In that case how must we create an object so that the constructor will also be called.
Er...use new? That's kind of the point. You can also call the constructor explicitly, but there's little reason to do it that way Using new/delete normally: A* a = new A(); delete a; Calling the constructor/destructor explicitly ("placement new"): A* a = (A*)malloc(sizeof(A)); new (a) A(); a->~A(); free(a);
2,995,251
2,995,258
Why in C++ do we use DWORD rather than unsigned int?
I'm not afraid to admit that I'm somewhat of a C++ newbie, so this might seem like a silly question but.... I see DWORD used all over the place in code examples. When I look up what a DWORD truly means, its apparently just an unsigned int (0 to 4,294,967,295). So my question then is, why do we have DWORD? What does it ...
DWORD is not a C++ type, it's defined in <windows.h>. The reason is that DWORD has a specific range and format Windows functions rely on, so if you require that specific range use that type. (Or as they say "When in Rome, do as the Romans do.") For you, that happens to correspond to unsigned int, but that might not alw...
2,995,337
2,995,486
How do I get through proxy server environments for non-standard services?
I'm not real hip on exactly what role(s) today's proxy servers can play and I'm learning so go easy on me :-) I have a client/server system I have written using a homegrown protocol and need to enhance the client side to negotiate its way out of a proxy environment. I have an existing client and server system written ...
If your software can make an SSL connection on port 443, then you are 99% of the way there. Typically HTTP proxies are set up to proxy SSL-on-443 (for the purposes of HTTPS). You just need to teach your software to use the HTTP proxy. Check the HTTP RFCs for the full details, but the Cliffs Notes version is: Connect...
2,995,513
2,995,564
Using C++ DLL in C# project
I got a C++ dll which has to be integrated in a C# project. I think I found the correct way to do it, but calling the dll gives me this error: System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B) This is the function in the dll: extern long...
try to use __stdcall (or WINAPI or APIENTRY) in the function exported from the DLL.
2,995,728
2,995,776
Is `std::string(strerror(errno))` dangerous?
At some places in my code, I print debug messages like this: int ret = getLinkSpeed(device.getSysName(), linkSpeed); if (ret < 0) { logDebug("Failed to obtain port speed for this device. Error: " + std::string(strerror(errno))); } From the documentation it is not entirely clear if strerror will return 0 under cert...
Why not write a function to do this: string ErrStr() { char * e = strerror(errno); return e ? e : ""; } This is easy to use, self-documenting, can be adapted to reformat the output and covers the possibility that strerror() might return NULL (I don't know if it can).
2,995,774
2,996,558
Bizarre static_cast trick?
While perusing the Qt source code I came across this gem: template <class T> inline T qgraphicsitem_cast(const QGraphicsItem *item) { return int(static_cast<T>(0)->Type) == int(QGraphicsItem::Type) || (item && int(static_cast<T>(0)->Type) == item->type()) ? static_cast<T>(item) : 0; } Notice the static_cas...
This looks like a very dubious way to statically assert that the template parameter T has a Type member, and then verify its value is the expected magic number, like you state you are supposed to do. Since Type is an enum value, the this pointer is not required to access it, so static_cast<Item>(0)->Type retrieves the ...
2,995,957
2,999,717
How to get the Drive Letter for the DevicePath
I am using Win32 API. Really i do not understand how to get the drive letter for DevicePath of a USB stick . can you pls explain it to me ( what i have is SP_DEVICE_INTERFACE_DETAIL_DATA DevicePath using this Device path i get VID AND PID of the usb device my device path looks like below "\?\usb#vid_1a8d&pid_1000#35809...
The link I provided in your other question gives you all the information you need to do this. In semi-pseudocode: DiskDevice = CreateFile(DiskDevicePath); DiskDeviceNumber = DeviceIoControl(DiskDevice, IOCTL_STORAGE_GET_DEVICE_NUMBER); for each VolumeDevicePath in GetLogicalDriveStrings VolumeDevice = CreateFile(V...
2,995,990
2,996,014
Dubugging a program not run within the debugger and without a crash
I left a program running last night, it worked fine for about 5 hours and then one of its built-in self-diagnostic tests detected a problem and brought up a dialog box telling me the issue. The program was built with debug information (/Zi). Is it possible to somehow get the debugger started so I can examine the value ...
You can attach the debugger to the running process: Debug > Attach to Process... Just open up the program's solution first. Assuming you've still got the error dialog on the screen you can break into the program and work back up the call stack examining variables etc.
2,996,070
2,998,881
Serializing chinese characters with Xerces 2.6
I have a Xerces (2.6) DOMNode object encoded UTF-8. I use to read its TEXT element like this: CBuffer DomNodeExtended::getText( const DOMNode* node ) const { char* p = XMLString::transcode( node->getNodeValue( ) ); CBuffer xNodeText( p ); delete p; return xNodeText; } Where CBuffer is, well, just a buffer obje...
I've now solved it as follows. I'm still not sure this is the optimal solution though CBuffer DomNodeExtended::getText( const DOMNode* node ) const { XMLCh tempStr[100]; XMLString::transcode("LS", tempStr, 99); DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(tempStr); DOMWrite...
2,996,079
2,996,204
Simple cross-platform code benchmarking
I'm aware of tools in the Xcode utilities for monitoring and benchmarking applications, but I'd like to test a few different (low level) implementations of library components, preferably across osx/linux/windows. Is there any framework for code benchmarking, similar to say unit tests? I'd just like some convenient api ...
Unfortunately benchmarking (and timing in particular) is a very platform-specific thing. However I think boost::date_time supports nanosecond timestamps on at least windows, OS X and linux, which might be a good place to start. Memory usage is difficult to measure if shared libraries are involved, but if you don't want...
2,996,247
2,996,284
std::bad_cast from parent to child?
For simplicity, class Parent {} class Child1 : Parent {} class Child2 : Parent {} Elsewhere, I created instances of Child1 and Child2 and store it in same vector under Parent: // . . . in .h file, for example vector<Parent> vector_of_parent; // . . . in one particular method Child1 c1; Child2 c2; vector_of_parent.p...
Your std::vector is declared as std::vector<Parent>. It holds only instances of Parent - when you insert the Child1 and Child2 instances, they get sliced. If you want to use a vector of polymorphic objects with a common base class of Parent, you need to use a container of pointers (or, for ease of lifetime and memory m...
2,996,565
3,049,482
Needed environment for building gstreamer plugins in Windows
I've been strugling for two weeks to create an environment for building a gstreamer plugin on windows (needed for a songbird addon). I've installed MSYS, MinGW and Cygwin, then installed GStreamer OSSBuild, and I also downloaded the sources for Songbird, which come with their own precompiled version of gstreamer. I was...
you can install precompiled gstreamer packages for cygwin at cygwinports. there you will find installation instructions and a list of available packages. you should not need to build them from source.
2,996,667
2,996,747
C++ UTF-8 lightweight & permissive code?
Anyone know of a more permissive license (MIT / public domain) version of this: http://library.gnome.org/devel/glibmm/unstable/classGlib_1_1ustring.html ('drop-in' replacement for std::string thats UTF-8 aware) Lightweight, does everything I need and even more (doubt I'll use the UTF-XX conversions even) I really don't...
std::string is fine for UTF-8 storage. If you need to analyze the text itself, the UTF-8 awareness will not help you much as there are too many things in Unicode that do not work on codepoint base. Take a look on Boost.Locale library (it uses ICU under the hood): Reference http://cppcms.sourceforge.net/boost_locale/...
2,996,914
2,996,958
C++ typedef for partial templates
i need to do a typedef like this. template< class A, class B, class C > class X { }; template< class B, class C > typedef X< std::vector<B>, B, C > Y; I just found that it is not supported in C++. Can someone advise me on how to achieve the same through alternative means? Thanks, Gokul.
If you have a C++0x/C++1x compiler, that will be allowed with a slightly different syntax (it seems as if compilers don't still support this feature): template <typename B, typename C> using Y = X< std::vector<B>, B, C >; You can use other techniques, like defining an enclosed type in a templated struct (like Pieter s...
2,996,939
2,997,406
NSMutableArray Vs Stack
I am developing 2D game for iphone in Objectice-C.In this project I need to use stack, I can do it using STL(Standard template library) stacks or NSMutableArray, since this stack is widely used in the game which one is more efficient in terms of runtime speed and memory use? @interface CarElement : NSObject { std::st...
It is generally accepted that Objective-C is slower in most cases than C++. Objective-C greatest virtues are flexibility and reuse. The runtime linking that creates that flexibility imposes a considerable overhead. On the other hand, in the case of arrays, that overhead is usually trivial. In the case of a LIFO stack...
2,997,234
2,997,709
Invoking C++ code from Java (GCJ)
I'm trying to invoke C++ from Java using GCJ using the CNI, so far I'm able to invoke Java code from C++. How can I invoke C++ from Java using the CNI?
I'll extend somewhat on pcent's answer to read the GCJ/CNI Docs. I believe that the key is to understand the whole "CNI C++ class" concept. The creation of a CNI C++ class is explained in that page. You can call Java code from a CNI C++ class (provided you have generated header files) - that's what you already do (cal...
2,997,383
2,998,094
Audio Recording in C++
I was wondering, what was a good cross-platform utility for doing audio recording/ playback/ seeking in C++? I was thinking going the route of ALUT (OpenAL), but is there a better way? If not, do you guys know of any good tutorials/sample code for ALUT?
SFML and SDL have support for playing many different sound formats and are cross plattform. Neither of them provides you with means for recording audio. Then there is PortAudio which looks pretty active but I do have no experience with it at all.
2,997,450
2,997,527
The importance of knowing c++ for web application development
I'm a php developer and I want to broaden my knowledge base by learning a higher language (java, c#, c++). My specialty is in building web applications (ria etc). I'm trying to think of the appropriate path to take (hedging my bets so to speak) in terms of which language I should be focusing on. I love open source tech...
C++ only comes in play when you work on large applications where you need low-level language features to write back end with performance in mind. Java and C# are meant to boost your productivity. First of all, by taking care of memory management and offering a very functional class library. Java seems to be a less acti...
2,997,558
2,997,674
Better cout a.k.a coutn;
Guys would it be difficult to write coutn which would basically place newline symbol at the end of the input. While working with console (that's all I can do at the moment) I'm finding very tedious to write '\n' every time I want the line to be a new line. Or maybe it is already implemented?
To circumvent the multiple injections on a single line, you could use a temporary object. This temporary object would add the '\n' in its destructor. struct coutn { coutn(): os(cout) {} ~coutn() { os << '\n'; } template <typename T> coutn & operator<<(T const & x) { os << x; return *this; } private:...
2,997,670
2,997,849
What -W values in gcc correspond to which actual warnings?
Preamble: I know, disabling warnings is not a good idea. Anyway, I have a technical question about this. Using GCC 3.3.6, I get the following warning: choosing ... over ... because conversion sequence for the argument is better. Now, I want to disable this warning as described in gcc warning options by providing an a...
You can find out what option is associated with a given warning by using the -fdiagnostics-show-option option: $ gcc -fdiagnostics-show-option -Wall foo.c foo.c: In function ‘main’: foo.c:3: warning: suggest parentheses around assignment used as truth value [-Wparentheses] And my two cents about this: assuming there's...
2,997,732
2,999,386
How to convert an existing callback interface to use boost signals & slots
I've currently got a class that can notify a number of other objects via callbacks: class Callback { virtual NodulesChanged() =0; virtual TurkiesTwisted() =0; }; class Notifier { std::vector<Callback*> m_Callbacks; void AddCallback(Callback* cb) {m_Callbacks.push(cb); } ... void ChangeNodules() { ...
Compared to my other answer, this solution is much more generic and eliminates boilerplate code: #include <iostream> #include <boost/bind.hpp> #include <boost/signal.hpp> /////////////////////////////////////////////////////////////////////////////// // GENERIC REUSABLE PART FOR ALL SUBJECTS //////////////////////////...
2,998,216
2,998,374
Does Qt support virtual pure slots?
My GUI project in Qt has a lot of "configuration pages" classes which all inherit directly from QWidget. Recently, I realized that all these classes share 2 commons slots (loadSettings() and saveSettings()). Regarding this, I have two questions: Does it make sense to write a intermediate base abstract class (lets name...
Yes, just like regular c++ pure virtual methods. The code generated by MOC does call the pure virtual slots, but that's ok since the base class can't be instantiated anyway... Again, just like regular c++ pure virtual methods, the class cannot be instantiated until the methods are given an implementation. One thing: in...
2,998,452
2,998,664
Bidirectional iterators in unordered_map?
The following minimal example: #include <iostream> #include <boost/unordered_map.hpp> int main() { boost::unordered_map<int, int> m; boost::unordered_map<int, int>::const_iterator i; m.insert(std::make_pair(1, 2)); i = m.end(); --i; std::cout << i->first << " -> " <<...
There is no technical reason why an unordered_map can't have bidirectional iterators. The main reason is that it would add additional cost to the implementation, and the designers thought nobody would really need bidirectional iterators in a hash map. After all, there's no order in a hash, and so the order the iterat...
2,998,632
2,998,740
Prefill a std::vector at initialization?
I want to create a vector of vector of a vector of double and want it to already have (32,32,16) elements, without manually pushing all of these back. Is there a way to do it during initialization? (I don't care what value gets pushed). I want a 3-dimensional array, the first dimension has 32, the second dimension has ...
One liner: std::vector< std::vector< std::vector<double> > > values(32, std::vector< std::vector<double> >(32, std::vector<double>(16, 0.0))); Or breaking the lines: typedef std::vector<double> v_type; typedef std::vector<v_type> vv_type; typedef std::vector<vv_type> vvv_type; vvv_type values(32, vv_type(32, v_type(1...
2,998,691
2,998,950
How to read direct3d texture pixels
So I have a x8r8g8b8 formatted IDirect3DSurface9 that contains the contents of the back buffer. When I call LockRect on it I get access to a struct containing pBits, a pointer to the pixels I assume, and and integer Pitch (which I am very unclear about its purpose). How to read the individual pixels? Visual Studio 2...
The locked area is stored in a D3DLOCKED_RECT. I haven't ever used this but the documentation says it is the "Number of bytes in one row of the surface". Actually people would normally call this "stride" (some terms explained in the MSDN). For example, if one pixel has 4 bytes (8 bits for each component of XRGB), and t...
2,998,864
2,998,876
How to add a 'or' condition in #ifdef
How can I add a 'or' condition in #ifdef ? I have tried: #ifdef CONDITION1 || CONDITION2 #endif This does not work.
#if defined(CONDITION1) || defined(CONDITION2) should work. :) #ifdef is a bit less typing, but doesn't work well with more complex conditions
2,998,875
2,999,469
Translating 3-dimensional array reference onto 1-dimensional array
If there is an array of ar[5000] then how could I find where element [5][5][4] would be if this was a 3 dimensional array? Thanks I'm mapping pixels: imagine a bimap of [768 * 1024 * 4] where would pixel [5][5][4] be? I want to make this: static GLubyte checkImage[checkImageHeight][checkImageWidth][4]; static GLuint t...
[x * z_size * y_size + y * z_size + z] worked
2,998,952
2,999,261
Internal "Tee" setup
I have inherited some really old VC6.0 code that I am upgrading to VS2008 for building a 64-bit app. One required feature that was implemented long, long ago is overriding std::cout so its output goes simultaneously to a console window and to a file. The implementation depended on the then-current VC98 library implem...
You could write a custom stream buffer and attach it to cout with cout.rdbuf(). Your custom stream buffer would then tee the data to cout's original stream buffer and to a stream buffer stolen from an appropriate ofstream. ofstream flog("log.txt"); teebuf tb(flog.rdbuf(), cout.rdbuf()); cout.rdbuf(&tb); For your teein...
2,999,012
2,999,028
generating random enums
How do I randomly select a value for an enum type in C++? I would like to do something like this. enum my_type(A,B,C,D,E,F,G,h,J,V); my_type test(rand() % 10); But this is illegal... there is not an implicit conversion from int to an enum type.
How about: enum my_type { a, b, c, d, last }; void f() { my_type test = static_cast<my_type>(rand() % last); }
2,999,016
2,999,045
Print numbers sequentially using printf with filling zeroes
in C++, using printf I want to print a sequence of number, so I get, from a "for" loop; 1 2 ... 9 10 11 and I create files from those numbers. But when I list them using "ls" I get 10 11 1 2 .. so instead of trying to solve the problem using bash, I wonder how could I print; 0001 0002 ... 0009 0010 0011 and so on Th...
i = 45; printf("%04i", i); => 0045 Basically, 0 tells printf to fill with '0', 4 is the digit count and 'i' is the placeholder for the integer (you can also use 'd'). See Wikipedia about the format placeholders.
2,999,135
2,999,161
How can I sort the vector elements using members as the key in C++
suppose we have a vector<student> allstudent Now I would like to sort the students using different memebers,such as name, age, address, like that. How can I do that?
Create a functor to compare the correct field, then specify the functor when you sort: struct by_age { bool operator()(student const &a, student const &b) const { return a.age < b.age; } }; struct by_name { bool operator()(student const &a, student const &b) const { return a.name < b.na...
2,999,330
3,603,923
C++ - SDL not working
I've tried to follow this tutorial on the basics of displaying an image with SDL. But, when I run the program, it returns a blank screen. The image is in the correct directories, but it doesn't display in the program. Am I doing something wrong? I'd really like SDL to work. EDIT Here is my code: #include <SDL/SDL.h>...
I thought I said I had fixed this months ago, seems as though I had not. I recompiled it again and it worked, very strange.
2,999,381
2,999,524
Void pointer cast C++ and GTK
See this GTK callback function: static gboolean callback(GtkWidget *widget, GdkEventButton *event, gpointer *data) { AnyClass *obj = (AnyClass*) data; // using obj works } (please note the gpointer* on the data). And then the signal is connected using: AnyClass *obj2 = new AnyClass(); gtk_signal_connect(/*GTK ...
It's not exactly safe, especially since in using c-style casts you've gone from doing a static_cast from T1* to void*, to a reinterpret_cast from T1* to void**. However, it works because the standard guarantees that you can reinterpret_cast from T1* to T2* (in this case T2=void*) and back again to get the same T1* you...
2,999,506
2,999,666
Non-member conversion functions; Casting different types, e.g. DirectX vector to OpenGL vector
I am currently working on a game "engine" that needs to move values between a 3D engine, a physics engine and a scripting language. Since I need to apply vectors from the physics engine to 3D objects very often and want to be able to control both the 3D, as well as the physics objects through the scripting system, I ne...
I would suggest writing them as a pair of free functions (i.e. don't worry about making them 'operators'): vector3d<float> vector3dFromBt(const btVector3& src) { // convert and return } btVector3 btVectorFrom3d(const vector3d<float>& src) { // convert and return } void f(void) { vector3d<float> one; // ....
2,999,537
2,999,609
STL: writing "where" operator for a vector
I need to find the indexes in the vector based on several boolean predicates. ex: vector<float> v; vector<int> idx; idx=where( bool_func1(v), bool_func2(v), ... ); What is the way to declare **where** function, in order to use the several user defined boolean functions over the vector? thanks Arman. Edit after one ...
Make your bool_xxx functions actually functors of a specific kind of type (tag dispatching would be enough). Then override || and && for them such that these operators return a bool_and, or bool_or. Then you can use your bool_ predicates like so: std::find_if(vect.begin(), vect.end(), bool_x1() || bool_x2() && (bool...
2,999,576
2,999,588
What does ~0 mean in this code?
What's the meaning of ~0 in this code? Can somebody analyze this code for me? unsigned int Order(unsigned int maxPeriod = ~0) const { Point r = *this; unsigned int n = 0; while( r.x_ != 0 && r.y_ != 0 ) { ++n; r += *this; if ( n > maxPeriod ) break; } return n; }
~0 is the bitwise complement of 0, which is a number with all bits filled. For an unsigned 32-bit int, that's 0xffffffff. The exact number of fs will depend on the size of the value that you assign ~0 to.
2,999,605
2,999,617
Doing a "less than" test with CppUnit
I am new to CppUnit. Is there any way to assert that a value must be less than zero? I am looking for something with similar behavior to CPPUNIT_ASSERT_EQUAL(). I was thinking there might be a test function named something like CPPUNIT_ASSERT_LESS_THAN().
How about CPPUNIT_ASSERT(variable < 0);?
2,999,772
2,999,819
C++ Virtual Methods for Class-Specific Attributes or External Structure
I have a set of classes which are all derived from a common base class. I want to use these classes polymorphically. The interface defines a set of getter methods whose return values are constant across a given derived class, but vary from one derived class to another. e.g.: enum AVal { A_VAL_ONE, A_VAL_TWO, A_VA...
The first method seems clearer and forces you to override those methods (at the first child anyway). I think the overhead of virtual calls tends to be less than one might expect. Only if you profile the code and the virtual calls are taking a ton of time would I attempt to do optimizations as in your second approach. T...
2,999,814
2,999,996
Locking a GDI+ Bitmap in Native C++?
I can find many examples on how to do this in managed c++ but none for unmanaged. I want to get all the pixel data as efficiently as possible, but some of the scan0 stuff I would need more info about so I can properly iterate through the pixel data and get each rgba value from it. right now I have this: Bitmap *b = n...
lockdat->Scan0 is a pointer to the pixel data of the bitmap. Note that you really do care what pixel format you ask for, PixelFormatDontCare won't do. Because how you use the pointer is affected by the pixel format. PixelFormat32bppARGB is the easiest, one pixel will be the size of an int, 4 bytes representing alpha...
2,999,952
3,048,082
Serializing QGraphicsScene contents
I am using the Qt QGraphicsScene class, adding pre-defined items such as QGraphicsRectItem, QGraphicsLineItem, etc. and I want to serialize the scene contents to disk. However, the base QGraphicsItem class (that the other items I use derive from) doesn't support serialization so I need to roll my own code. The proble...
I agree with the other posters, the QGraphicsItem could really be viewed as a view item and so separating your model data into its own class would probably be better. That said, I think your crash is caused by an inappropriate cast. If you do the following: Rect *r = new Rect(); QGraphicsItem *qi = reinterpret_cast<QGr...
3,000,132
3,000,223
C++ code to check the status of a process if it is Running, Stopped, Sleeping or a Zombie on linux from its pid
I am kind of creating a watchdog which keeps the status log of other processes whose pids are known. I wana know if there is some c++ or c code to get this functionality.
You can read /proc/{PID}/status and parse the line beginning with "State:".
3,000,138
3,000,246
Can typeid() be used to pass a function?
I tried this and got the output as: void Please explain the following Code: #include <cstdio> #include <typeinfo> using namespace std ; void foo() { } int main(void) { printf("%s", typeid(foo()).name());// Please notice this line, is it same as typeid( ).name() ? return 0; } AFAIK: The typeid operator...
typeid does not work with objects. It works with expressions. typeid returns the type of the expression you supply to it as an argument. The expression can refer to an object, or to something that is not an object. You supplied expression foo() as an argument. This expression has type void. So, you got a result that r...
3,000,231
3,738,906
D_WIN32_WINNT compiler warning with Boost
Not sure what to make of this error. Added -D_WIN32_WINNT=0x0501 to Visual Studio's "Command Line" options under Project Properties but it says it doesn't recognize it and the warning still appears. I am also not sure how to add the Preprocessor Definition. 1>Please define _WIN32_WINNT or _WIN32_WINDOWS appropriate...
I think you're really close to getting this to work. John Dibling gave three ways you could do this and it looks like you tried the third solution, which was to "go in to your project's settings ... and under the Configuration Properties->C/C++->PreProcessor heading, add ;_WIN32_WINNT = 0x0501". You replied that you ...
3,000,579
3,000,593
access elements of a void *?
I have a void pointer and want to access elements from it. How could I transform a void * into an unsigned byte pointer so I can access its elements (which I know are actually unsigned bytes). Thanks Using C++
You need to cast it to the appropriate type you are using for an "unsigned byte". Once it's casted appropriately, you can access it as if it is an array (access elements). unsigned char* bytePointer = static_cast<unsigned char*>(originalVoidPointer); unsigned char elementFive = bytePointer[5];
3,000,736
3,000,959
C++ linker error when trying to compile a second module using Code::Blocks
So I'm trying to learn C++ and I've gotten as far as using header files. They really make no sense to me. I've tried many combinations of this but nothing so far has worked: Main.cpp: #include "test.h" int main() { testClass Player1; return 0; } test.h: #ifndef TEST_H_INCLUDED #define TEST_H_INCLUDED class t...
Code::Blocks doesn't know that it has to compile test.cpp and produce an object file test.o (so that the latter may be linked together with main.o to produce the executable). You have to add test.cpp to your project. In Code::Blocks, go to Project>Add File in the menu and select your test.cpp file. Make sure that both ...
3,000,739
3,000,772
C++: Allocation of variables in a loop
Let's say I have a loop like this: vector<shared_ptr<someStruct>> vec; int i = 0; while (condition) { i++ shared_ptr<someStruct> sps(new someStruct()); WCHAR wchr[20]; memset(wchr, i, 20); sps->pwsz = wchr; vec.push_back(sps); } At the end of this loop, I see that for each sps element of...
I don't think this code does what you expect it to. You probably want wchr created on the heap or as a member of someStruct. wchr is allocated on the stack and gets freed on each iteration. The stack location will be the same on each iteration (probably the same). Each of your smart pointers contains a pointer to th...
3,000,891
3,001,003
How can I get the same strstream functionality now that's deprecated?
I use to write code like this: void fun(char *buff, unsigned size) { std::strstream str(buff, size); str << "hello world: " << 5; } so I can use stream output over an arbitrary buffer. I've found this technique both efficient (no allocations) and useful (streams!). Now that std::strstream is deprecated, how ca...
The standard library doesn't provide that functionality. However, Boost does with its generic streams and array sources/sinks. Boost Generic Stream Boost Array Devices char buff[size]; boost::stream<boost::array_sink> out(buff, size); out << "Hello, world!"; (Code untested)