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() { int test[] = {1,2,3}; std::cout << test[0] << test[1] << test[2]; test = {4,5,6}; std::cout << test[0] << test[1] << test[2] << std::endl; } and it prints 123456. Is GCC correct here?
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 plain wrappers like (and let's say the number of these wrappers equals 2 or 3): void FooToFile(const std::string& filename, Object& object) { std::ifstream stream(filename.c_str()); Foo(stream, object); } So, my question is: Where in this case (ideologically) should I throw the exception if my stream is bad? Should I do this in each wrapper or just move that check to my Foo, so that it's body would look like if (!foo.good()) throw (something); // Perform ordinary actions I understand that this may be not the most important part of coding and these solutions are actually equal, but I just wan't to know "the proper" way to implement this. Thank you.
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 redundantly at multiple levels in the call stack.
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 (compiled without RTTI). In theory, is all that supposed to compile and link with no problems?
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 doesn't barf when I try to load the PNG, but it never gets displayed. If someone would post a simple program to load a PNG from a file and display it, it would greatly appreciated. (I know, asking a lot, but...). Thanks! :bp:
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 will automatically chose an appropriate reader according to the format of the image it detects in step 1.
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 RGB component values are between 0 and 1 (multiplied by 255).
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 1,2 already exist so in total I have stored 1,2,3 As you can see, we can easily check for new values, if old != new. Here's come the problem: Fourth trigger: You get 1, 2, 4 For 4th trigger, I store 1, 2 because it exists but how do I check against 3 and remove 3 from store and check if 4 is new? If you are having problems understanding this, feel free to clarify. Thanks!
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 defined), but I was wondering whether it would be better to use this: static LPCTSTR szWindowClass = TEXT("MyApp"); Or this: static const TCHAR szWindowClass[] = TEXT("MyApp"); I personally prefer the use of the LPCTSTR as coming from a JavaScript, PHP, C# background I never really considered declaring a string as an array of chars. But are there actually any advantages of using one over the other, or does it in fact not even make a difference as to which one I choose? Thank you, in advanced, for your answers.
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 LPCTSTR is: static const TCHAR * szWindowClass = TEXT("MyApp"); The "L" in LPCTSTR stands for "Long", which hasn't been relevant since 16-bit Windows programming and can be ignored.
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 wrong?
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; ++idx ) { { boost::mutex::scoped_lock l(m); std::cout << "function " << n << ", ping " << idx << std::endl; } sleep(1); } } private: int n; }; /***************************************************************************/ int main(int argv, const char** argc) { boost::asio::io_service io; for ( int idx = 0; idx < 4; ++idx ) { io.post(func(idx)); } std::cout << "before run" << std::endl; io.poll(); std::cout << "after run" << std::endl; std::cin.get(); return 0; } /***************************************************************************/ gives such an output: **before run** run function 0 function 0, ping 0 function 0, ping 1 function 0, ping 2 function 0, ping 3 run function 1 function 1, ping 0 function 1, ping 1 function 1, ping 2 function 1, ping 3 run function 2 function 2, ping 0 function 2, ping 1 function 2, ping 2 function 2, ping 3 run function 3 function 3, ping 0 function 3, ping 1 function 3, ping 2 function 3, ping 3 **after run** but, according to the documentation: The poll() function runs handlers that are ready to run, without blocking, until the io_service has been stopped or there are no more ready handlers. poll() - is a non-blocking method. what's the problem? and the second question: in documentation it is said that: return The number of handlers that were executed. if it is non-blocking, what value it will return? - the number of objects in the queue? - but this is not the same thing as "that were executed".
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 ready handlers, and will not return until there are no more handlers ready to be dispatched. The difference in other words is that run will wait for a pending handler to be ready, like a timer or IO completion notification, while poll will return in that situation. This behavior is useful if you want to perform some idle processing.
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_str() returns a pointer into that object, and at the end of the assignment that temporary object will be destructed. What you can do instead is either f(wss.str().c_str()); // fine if f() doesn't try to keep the pointer or const std::wstring& wstr = wss.str(); // extends lifetime of temporary const LPCWSTR p = wstr.c_str(); f(p); // fine, too because temporary objects bound to a const reference will have their lifetime extended for the reference's lifetime.
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: Take the following function that processes an incoming std::vector and builds a running total of many data-points/iterations of a process: /* the for-loop method - not very savvy */ void UpdateRunningTotal (int_vec& total, int_vec& data_point) { for (int i = 0; i < V_SIZE; i++) { total[i] += data_point[i]; } } typedef int_vec std::vector<int>; int_vec running_total (V_SIZE, 0); // create a container to hold all the "data points" over many iterations /* further initialization, and some elaborate loop to create data points */ UpdateRunningTotal (running_total, iteration_data); /* further processing */ The above works, but I'd much rather have a function that takes iterators and performs this summation. Even better, have a generic parameter list with the type deduced instead of specifying the container type, i.e.: UpdateRunningTotal (iteration_data.begin(), iteration_data.end(), running_total.begin()); I'm really lost at this point and need a little guidance to find how to define the template and argument lists to make the function generic. What would the template and function definition look like? I'm already familiar with a way to perform this specific task using STL functionality - I'm looking for illustration of the generic function/template definition.
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, Iter2 pBegin2) { typedef typename std::iterator_traits<Iter1>::value_type value_type; std::transform(pBegin, pEnd, pBegin2, pBegin, std::plus<value_type>()); }
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\boost\config\auto_link.hpp 2 IntelliSense: #error directive: "some required macros where not defined (internal logic error)." c:\boost_1_43_0\boost\config\auto_link.hpp Checking the auto_link.hpp header file the first error is in this line #ifndef BOOST_LIB_NAME # error "Macro BOOST_LIB_NAME not set (internal error)" #endif Tracing the definition of BOOST_LIB_NAME, it seems that is defined in config.hpp by boost_regex, which code I am including below #if !defined(BOOST_REGEX_NO_LIB) && !defined(BOOST_REGEX_SOURCE) && !defined(BOOST_ALL_NO_LIB) && defined(__cplusplus) # define BOOST_LIB_NAME boost_regex # if defined(BOOST_REGEX_DYN_LINK) || defined(BOOST_ALL_DYN_LINK) # define BOOST_DYN_LINK ... more code and strangely when I point to BOOST_LIB_NAME it defines BOOST_LIB_NAME and the IntelliSense errors disappear. My program builds and executes fine using the Boost:Regex library -- with or without the Intellisense errors; however, I do not understand why these IntelliSense errors appear in the first place, and second why pointing the macro in the config.hpp defines BOOST_LIB_NAME. Any guidance will be greatly appreciated. Thanks, Jaime
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 created it using New Project -> Empty project. I added main.cpp that contains this: #include <iostream> using namespace std; int main() { cout << "howdy\n"; } I added new configuration to the project by clicking on Config Manager and added x64 config. Compiled and it compiles. Tried running it and cmd.exe shoots up with following error: "The application has failed to start because its side-by-side configuration is in correct. Please see the application event log or use the command-line sxstrace.e xe tool for more detail. Press any key to continue . . . " Which set-up step if any I am missing. What am I doing wrong and how should I go about setting simple console hello world in 64 bit world. Thanks for any help
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 init function (A_init, defined in A/initA.cpp), that is called from library B's init function (B_init, defined in B/initB.cpp), which is called from C's main. Thus, when linking B, A_init (and all symbols defined in initA.cpp) is linked into B (which is our desired behavior). The problem comes in that the A library also defines a function (Af, defined in A/Afort.f) that is intended to by dynamically loaded (i.e. LoadLibrary/GetProcAddress on Windows and dlopen/dlsym on Linux). Since there are no references to Af from library B, symbols from A/Afort.o are not included into B. On Windows, we can artifically create a reference by using the pragma: #pragma comment (linker, "/export:_Af") Since this is a pragma, it only works on Windows (using Visual Studio 2008). To get it working on Linux, we've tried adding the following to A/initA.cpp: extern void Af(void); static void (*Af_fp)(void) = &Af; This does not cause the symbol Af to be included in the final link of B. How can we force the symbol Af to be linked into B?
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)) # else # define FORCE_UNDEFINED_SYMBOL(x) __pragma(comment (linker, "/export:_" #x)) # endif #else # define FORCE_UNDEFINED_SYMBOL(x) extern "C" void x(void); void (*__ ## x ## _fp)(void)=&x; #endif Which is used thusly: FORCE_UNDEFINED_SYMBOL(Af)
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 program can install itself as a service on the local machine, and start the service. Said service now runs under the SYSTEM account, which enables us to use our SeTCBPrivilege privilege to create a new access token which does have SeDebugPrivilege. We can then use the newly created token to re-launch the initial program with the elevated rights. I personally do not like this solution. I feel it should be possible to acquire the necessary privileges as an Administrator without having to make system modifications such as installing a service (even if it is only temporary). I am hoping that there is a solution that minimizes system modifications and can preferably be done on the fly (ie: Not require restarting itself). I have unsuccessfully tried to LogonUser as SYSTEM and tried to OpenProcessToken on a known SYSTEM process (such as csrss.exe) (which fails, because you cannot OpenProcess with PROCESS_QUERY_INFORMATION to get a handle to the process without the privileges I'm trying to acquire). I'm just at my wit's end trying to come up with an alternative solution to this problem. I was hoping there was an easy way to grab a privileged token on the host machine and impersonate it for this program, but I haven't found a way. If anyone knows of a way around this, or even has suggestions on things that might work, please let me know. I really appreciate the help, thanks!
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 exactly what you're trying to do. If you want to be able to remove your service afterwards, simply grant the user in question SeDebugPrivilege for the local machine and then have the service uninstall itself. Better yet, have the program whose memory is to be modified change DACLs to allow your administrator access to it's memory without SeDebugPrivilege. Then you don't need to take privilege at all. EDIT2: And even better yet, just use shared memory in the first place. That's what it's for.
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 strip_diacritics( UnicodeString const &s ) { UnicodeString result; // ... return result; } Assume that s has already been normalized. Thanks.
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 string buf8; buf8.reserve( s8.length() ); for ( string::const_iterator i = s8.begin(); i != s8.end(); ++i ) { char const c = *i; if ( isascii( c ) ) buf8.push_back( c ); } // result is in buf8 which is O(n).
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 AN ANSWER BELOW BUT MODIFED TO CAUSE THE PROBLEM I AM HAVING, here we go: Ok i have been able to reproduce my error with this code: class ClassA { public: virtual ~ClassA(){} }; template <class Param1 = void*> class ClassB : public ClassA { public: //constructor ClassB(Param1 p1 = NULL) { _p1 = p1; } //ClassB(const ClassB<Param1>& ref); Param1 _p1; ~ClassB(){} }; enum lolcakes { cakeisalie, }; ClassA* ptr = new ClassB<lolcakes>(lolcakes::cakeisalie); ClassB<lolcakes>* a1 = (ClassB<lolcakes>*)ptr;
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 the missing argument to the constructor). Now, your cast syntax is wrong in both cases. The parentheses need to go around the type only. But better use a static_cast anyway: ClassA_1<myenum>* a1 = static_cast<ClassA_1<myenum>*>(a); This works. UPDATE After question edit: The important error is in this line: ClassB(Param1 p1 = NULL) you cannot use NULL as the default parameter since your Param1 type is not a pointer – it’s an enum (strictly speaking this should work since NULL is defined as being equal to 0 in C++, but it’s a logical error nonetheless). Instead of making the parameter optional, a better alternative would be to overload the constructor. Alternatively, the following also works: ClassB(Param1 p1 = Param1()) This uses the default value for the type Param1. There’s an additional error in the code: ClassA* ptr = new ClassB<lolcakes>(lolcakes::cakeisalie); Enum constants don’t work like that in C++: They don’t create an own namespace, hence their usage cannot be qualified. Instead, omit the enum’s name: ClassA* ptr = new ClassB<lolcakes>(cakeisalie); Finally, please don’t use C-style casts, ever. Always replace them with the appropriate C++-style casts. In your case, replace ClassB<lolcakes>* a1 = (ClassB<lolcakes>*)ptr; with ClassB<lolcakes>* a1 = boost::polymorphic_downcast<ClassB<lolcakes>*>(ptr); // or ClassB<lolcakes>* a1 = static_cast<ClassB<lolcakes>*>(ptr);
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()->size()); } protected: void paintEvent(QPaintEvent*) { QPainter painter(this); painter.fillRect(geometry(), Qt::white); } }; The problem with this solution is that it completely paints over everything that your desktop environment draws in the background (including icons, plasmoids,...). If you just want to set a new background image programmatically, I would check if your DE has an API for that.
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 stuff with points ... delete [] pArray; } I realize that this code is atrociously wrong on so many levels (C-style cast, using new like malloc, confusing, etc). I also realize that if Point had defined a constructor it would not be called and weird things would happen at delete [] if a destructor had been defined. Question: I am in the process of fixing these occurrences wherever they appear as a matter of course. However, I have never seen anything like this before and it has got me wondering. Does this code have the potential to cause memory leaks/corruption as it stands currently (no constructor/destructor, but with pointer type mismatch) or is it safe as long as the array just contains structs/primitive types?
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 trivial constructor and destructor), then this correction solves all formal issues there are in this code. From the language point of view, the lifetime of an object with trivial constructor (destructor) begins (ends) simultaneously with its storage duration. I.e. there's no requirement to perform the actual invocation of constructor (destructor).
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 over another application's menus? Or is there something built in to windows that ensures that menus in the currently active application are always drawn on top? In fact, I don't really understand all that well how menus work. So it might not even make any sense for me to try to make my window "act like a menu" in hopes of making it cover more things.
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: How do I display a useful vertical scrollbar for this view? I’ve seen cases (notably web browsers) where the slider “jumps away” from the mouse cursor while the user is dragging it, the result of the underlying content growing in height. I don’t want that. So far Instead of the slider representing the viewport height relative to the content height, maybe it could represent a point in a timeline instead? (The items are sorted by timestamp). This would at least prevent the scrollbar from changing as item layouts are calculated. Get rid of the scrollbar altogether and use a forward/backward rocker switch like the one used in Picasa (the further the slider is pulled upwards or downwards, the faster the view is scrolled, until the user releases the slider). If I take this route, are there any controls you can recommend? I am using Qt, but this applies to UI design in general.
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 rocker (is that an official name?) would be the next best thing to use. However, since you have a dedicated scale (timeline), it might be better to have separate buttons that jump a dedicated time (e.g. one minute, one hour, one day, ..). For a fancier look, you could create a rocker with "hot" areas that jump for a specific time, whereas the areas inbetween are interpolated (linear or or logarithmic, depending on the scale to cover). i.e. line this (drawing just the "backward" half): -------------------------- |##|XXXXXXX|##|XXXXXXX|##| -------------------------- -1h -1m -1s
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 (int a); // user information int userHP = 100; int userAtk = 10; int userDef = 5; string userName; //enemy Information int enemyHP; int enemyAtk; int enemyDef; string enemies[] = {"Raider", "Bandit", "Mugger"}; int sizeOfEnemies = sizeof(enemies) / sizeof(int); string currentEnemy; int chooseEnemy; // ACTIONS int journey; int test; int main() { // main menu cout << "welcome brave knight, what is your name? " ; cin >> userName; cout << "welcome " << userName << " to Darland" << endl; //TRAVELING MENU: cout << "where would you like to travel? " << endl; cout << endl << " 1.> Theives Pass " << endl; cout << " 2.> Humble Town " << endl; cout << " 3.> Mission HQ " << endl; cin >> journey; if (journey == 1) { // action variable; string c_action; cout << "beware your journey grows dangerous " << endl; //begins battle // Creating the enemy, HP ATK DEF AND TYPE. ; srand(time(0)); enemyHP = create_enemyHP(userHP); enemyAtk = create_enemyAtk(userAtk); enemyDef = create_enemyDef(userDef); chooseEnemy = find_Enemy(sizeOfEnemies); currentEnemy = enemies[chooseEnemy]; cout << " Here comes a " << currentEnemy << endl; cout << "stats: " << endl; cout << "HP :" << enemyHP << endl; cout << "Attack : " << enemyAtk << endl; cout << "Defense : " << enemyDef << endl; ACTIONS: cout << "Attack <A> | Defend <D> | Items <I>"; cin >> c_action; //if ATTACK/DEFEND/ITEMS choice if (c_action == "A" || c_action == "a"){ enemyHP = enemyHP - userAtk; cout << " you attack the enemy reducing his health to " << enemyHP << endl; userHP = userHP - enemyAtk; cout << "however he lashes back causing you to have " << userHP << "health left " << endl; //end of ATTACK ACTION } the last line "cin >> c_action crashes. i use two other pages. they just create the functions. is it a complier issue. also why does my complier always shutdown after it runs he app. is there a way to stop it?
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 access "a". Surely I'm missing something small but still very confused. :P (Even without the invalid access of "a" the constructor isn't called when calling testMethod() from main. class IPAddressResolver { private: public: static int a; IPAddressResolver(); static void TestMethod(); }; IPAddressResolver::IPAddressResolver() { IPAddressResolver::a = 0; cout << "Creating IPAddressResolver" << endl; } void IPAddressResolver::TestMethod() { cout << "testMethod" << endl; }
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 not called, since you don't create a new instance of the class. For a static utility class, you don't need instances, so you can omit the constructor altogether. Alternatively, you might want to declare it private to make it explicit that the class shall not be instantiated (see above). Notes: it is not recommended to use public fields in classes, so I turned a into private, static utility classes are usually stateless, so if you need to have fields within your class, this maybe a sign that the class would better be a Singleton.
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 am using gcc 4.4 with C++0x enabled.)
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()); } Use like: compressed_vector<double> vect = vector_cast<compressed_vector<double> >(my_sparse_vector);
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 "free". I have debugged this code many times, and there is nothing abnormal regarding the pointers. char buf[2000]; char *data = (char*)malloc(sizeof(buf)); unsigned int size = sizeof(buf); for (unsigned int i = 0; i < 5; ++i) { char *ptr = data + size; size += sizeof(buf); char *tmp = (char*)realloc(data, size); if (!tmp) { std::cout << "Oh no.."; break; } data = tmp; memcpy(ptr, buf, sizeof(buf)); } free(data); Thanks!
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 most of the code you need from there to store the changes in QTextDocument.
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 .c wrapper for the .cpp code (but then the .c wrapper doesn't "see" any .cpp symbols). I'm about to give up and use DLLs. Any suggestions?
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(){ fptrfunc(func,10); //this is ok fptrfunc([](int i){cout << "LAMBDA CALL " << i << endl; }, 20); //DOES NOT COMPILE return 0; }
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; cout << "2.p1: " << p1 << ", p2: " << p2 << endl; cout << "2.*p1: " << *p1 << ", *p2: " << *p2 << endl; *p2 = *p1; cout << "3.p1: " << p1 << ", p2: " << p2 << endl; cout << "3.*p1: " << *p1 << ", *p2: " << *p2 << endl; p1 = p2; cout << "4.p1: " << p1 << ", p2: " << p2 << endl; cout << "4.*p1: " << *p1 << ", *p2: " << *p2 << endl; *p1 = 20; cout << "5.p1: " << p1 << ", p2: " << p2 << endl; cout << "5.*p1: " << *p1 << ", *p2: " << *p2 << endl; cout << "firstvalue is " << firstvalue << endl; cout << "secondvalue is " << secondvalue << endl; cout << "firstvalue is " << &firstvalue << endl; cout << "secondvalue is " << &secondvalue << endl; getch(); return 0; } And here's the output : 1.p1: 0041FB40, p2: 0041FB34 1.*p1: 5, *p2: 15 2.p1: 0041FB40, p2: 0041FB34 2.*p1: 10, *p2: 15 3.p1: 0041FB40, p2: 0041FB34 3.*p1: 10, *p2: 10 4.p1: 0041FB34, p2: 0041FB34 4.*p1: 10, *p2: 10 5.p1: 0041FB34, p2: 0041FB34 5.*p1: 20, *p2: 20 firstvalue is 10 secondvalue is 20 firstvalue is 0041FB40 secondvalue is 0041FB34 What is copied in the line "p1 = p2" ? Does p1 become reference to p2 or does it work in different way ?
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 parameter. _tcsncmp(access, TEXT("ftp"), 3); //or do i want _tcsnccmp? "Supported on Windows platforms only, _mbsncmp and _mbsnbcmp are multibyte versions of strncmp. _mbsncmp will compare at most count multibyte characters and _mbsnbcmp will compare at most count bytes. They both use the current multibyte code page. _tcsnccmp and _tcsncmp are the corresponding Generic functions for _mbsncmp and _mbsnbcmp, respectively. _tccmp is equivalent to _tcsnccmp." A similar question is _tcslen vs _tcsclen.
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 keyword to override member functions?) mammal.h #ifndef MAMMAL_H_INCLUDED #define MAMMAL_H_INCLUDED #include <string> class Mammal { public: std::string ToString(); }; #endif // MAMMAL_H_INCLUDED mammal.cpp #include <string> #include "mammal.h" std::string Mammal::ToString() { return "I am a Mammal!"; } dog.h #ifndef DOG_H_INCLUDED #define DOG_H_INCLUDED #include <string> #include "mammal.h" class Dog : public Mammal { public: std::string ToString(); }; #endif // DOG_H_INCLUDED dog.cpp #include <string> #include "dog.h" std::string Dog::ToString() { return "I am a Dog!"; } main.cpp #include <iostream> #include "dog.h" using namespace std; int main() { Dog d; std::cout << d.ToString() << std::endl; return 0; } output I am a Dog! I'm using MingW on Windows via Code::Blocks.
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:: declaration is the first one found? virtual dispatch would only happen (and only be needed) when being called through a pointer or reference to a base class object. If you needed to call the base class method on a Dog object you would have to qualify it explicitly. d.Mammal::ToString()
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 your mesh. Now... If your mesh is a regular 2D grid (a special case), on which you want to map a texture uniformly (another special case), then yeah, linear interpolation of the texture coordinates based on the vertex positions would work.
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 done just after creating whole AST - starting from the root and going forward). For example: my_var = sqrt(9 ** 2 - 32) + 4 - 20 / 5 my_var * 3 Would be parsed as: = / \ my_var + / \ sqrt - | / \ - 4 / / \ / \ ** 32 20 5 / \ 9 2 and the second AST would look like: * / \ my_var 3 Then following pseudocode reflects AST: ast_root = create_node('=', new_variable("my_var"), exp) where exp is: exp = create_node(OPERATOR, val1, val2) but NOT like this: $$ = $1 OPERATOR $3 because this way I directly get value of operation instead of creation the Node. I believe the Node should contain type (of operation), val1 (Node), val2 (Node). In some cases val2 would be NULL, like above mentioned sqrt which takes in the end one argument. Right? It will be nice if you can propose me C++ skeleton (without evaluation) for above described problem (including *.y file creating AST) to help me understand the way of creating/holding Nodes in AST. Code can be snipped, just to let me get the idea. I'll also be grateful if you point me to an existing (possibly simple) example if you know any. Thank you all for your time and assistance!
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 "NiApi.dll" to generate wrappers/information, then ISrvrSessionPtr session(L"NiApi.SrvrSession"); to create object, then trying session->put_OnLogin(); to assign events, but there is no one put_On or such member. niapi.tlh have _ISrvrSessionEvents struct inside, but it have no relations with SrvrSession. I need to use events from NiApi::SrvrSession for handling connection status. Please help or my boss kill me! (sorry for broken english, I read better than speak;)
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 connection point of the GUID of the event interface. The you call its Advise method to connect it to your event sink. class CSrvrSessionEvents: public _ISrvrSessionEvents { public: HRESULT OnLogin(long LoginResult) { // do something return S_OK; } // implement rest of _ISrvrSessionEvents }; ISrvrSession* pSrvrSession = ...; // get ISrvrSession from somewhere _ISrvrSessionEvents* pSrvrSessionEvents = new CSrvrSessionEvents(); IConnectionPointContainer* pCPC = NULL; pSrvrSession->QueryInterface(IID_IConnectionPointContainer, &pCPC); IConnectionPoint* pCP = NULL; pCPC->FindConnectionPoint(__uuidof(_ISrvrSessionEvents), &pCP); DWORD dwCookie = 0; pCP->Advise(pSrvrSessionEvents, &dwCookie); pSrvrSession->Connect(); // I assume this fires some events pCP->Unadvise(dwCookie);
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::filesystem; void find_file(const path& root, const string& file_name, vector<path>& found_files) { directory_iterator current_file(root), end_file; bool found_file_in_dir = false; for( ; current_file != end_file; ++current_file) { if( is_directory(current_file->status()) ) find_file(*current_file, file_name, found_files); if( !found_file_in_dir && current_file->leaf() == file_name ) { // Now we have found a file with the specified name, // which means that there are no more files with the same // name in the __same__ directory. What we have to do next, // is to look for sub directories only, without checking other files. found_files.push_back(*current_file); found_file_in_dir = true; } } } int main() { string file_name; string root_path; vector<path> found_files; std::cout << root_path; cout << "Please enter the name of the file to be found(with extension): "; cin >> file_name; cout << "Please enter the starting path of the search: "; cin >> root_path; cout << endl; find_file(root_path, file_name, found_files); for( std::size_t i = 0; i < found_files.size(); ++i) cout << found_files[i] << endl; }
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 myvec[0][1] is less than myvec[1][1] then myvec[0] and myvec[1] will swap. Thanks
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 concept is the same.
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 ; i<count ; i++ ) { //placement new to call constructor new (&this->structPool[i].object) T(); } } ~MyClass() { for( size_t i=0 ; i<this->structCount ; i++ ) { //explicit destructor call this->structPool[i].object.~T(); } delete[] this->structPool; } } My question is, is this a safe way to do? Do I make some hidden mistake at some condition? Will it work for every type of object (POD and non-POD)?
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 example, there is no need for placement new or an explicit destructor call. Placement new would be useful if you allocate raw memory. For example, if you changed your new to: this->structPool = new char[sizeof(T) * count]; then you would want to placement new and explict destructor call.
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 library to my version control, but that usually seems to massively inflate the size of the branch and generally seem like a bad idea. Is that the normal practice, just pushing the required libraries, or is there a better way of added libraries to distributed version control like bzr or git? (I know on svn you can use svn:external to do something similar to this)
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 in your own.
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 sorted, you can use std::binary_search() to test whether a value is present in the vector, and std::equal_range() to get begin and end iterators to the range of elements in the vector that have that value.
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 <iostream> using namespace std; int main() { int sum; for(int x = 1; x <= 10; x++) { sum += x; } cout << "The sum is: " << sum << endl; return 0; } When I ran it it kept printing 32822 for the sum. I knew the answer was supposed to be 55 and realized that its print the max value for a short (32767) plus 55. Changing int sum; to int sum = 0; would work (as it should, since the variable needs to be initialized!). Why does this behavior happen, though? Why doesnt the compiler warn you about something like this? I know Java screams at you when something isnt initialized. Thank you. Edit: Im using g++. Here is the output from g++ --version: Im on Mac OS X and am using g++. nom24837c:~ omarestrella$ g++ --version i686-apple-darwin10-g++-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5646)
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 note when switching to C/C++. A program written in C++ is native and machine-level. It is not running on a VM or a some other sort of framework. It is a collection of raw operations (for the most part). You do not have a virtual machine running in the background checking you variables and catching exceptions or segfaults for you. This is a big difference which can lead to a lot of confusion in the way C++ handles variables and memory, as opposed to Java or a .Net language. Hell, in .Net all your integers are implicitly initialised to 0!
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 there any library or anyway to overload the extraction operator to make cin automatically typesafe?
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 write a function template that performs the extraction, tests whether it succeeded, resets the error state on the stream if appropriate, and returns whether the extraction succeeded along with the result.
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 // Deprecated in VC2008. // construct a std::string using the LPCSTR input std::string strStd (T2CA (cString)); #endif return strStd; } I did several simple tests and it seems to work fine. However, when I search the web I can see that most usages of T2CA in VC6 have a preceding call of USES_CONVERSION; Is there anything that I had missed? Should I invoke my function by : #else // Deprecated in VC2008. // construct a std::string using the LPCSTR input USES_CONVERSION; std::string strStd (T2CA (cString)); #endif
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+po3) /3 ); } when i try compiling this i get q2b.cpp:32: error: template declaration of `float average' q2b.cpp:32: error: missing template arguments before "ElemT" not quite sure what this means.
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 correct with respect to instantiation? why is not first instantiated as const T&? Thank you
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 (like, again, enumeration constants).
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 give us that the integral type 'unsigned int' does not? Does it have something to do with portability and machine differences?
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 always be the case. To be safe, use DWORD when a DWORD is expected, regardless of what it may actually be. For example, if they ever changed the range or format of unsigned int they could use a different type to underly DWORD to keep the same requirements, and all code using DWORD would be none-the-wiser. (Likewise, they could decide DWORD needs to be unsigned long long, change it, and all code using DWORD would be none-the-wiser.) Also note unsigned int does not necessary have the range 0 to 4,294,967,295. See here.
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 in C and C++ for the speed and a small amount of MFC in the client to handle the user interface. I have written both the server and client side of the system on Windows (the people I work for are mainly web developers using Windows everything - not a choice) sticking to Berkeley Sockets as it were via wsock32 for efficiency. The clients connect to the server through a nonstandard port (even though using port 80 is an option to get out of some environments but the protocol that goes over it isn't HTTP). The TCP connection(s) stay open for the duration of the clients participation in real time conferences. Our customer base is expanding to all kinds of networked environments. I have been able to solve a lot of problems by adding the ability to connect securely over port 443 and using secure sockets which allows the protocol to pass through a lot environments since the internal packets can't be sniffed. But more and more of our customers are behind a proxy server environment and my direct connections don't make it through. My old school understanding of proxy servers is that they act as a proxy for external HTML content over HTTP, possibly locally caching popular material for faster local access, and also allowing their IT staff to blacklist certain destination sites. Customer are complaining that my software doesn't recognize and easily navigate its way through their proxy environments but I'm finding it difficult to decide what my "best fit" solution should be. My software doesn't tear down the connection after each client request, and on top of that packets can come from either side at any time, basically your typical custom client/server system for a specific niche. My first reaction is "why can't they just add my server's addresses to their white list" but if there is a programmatic way I can get through without requiring their IT staff to help it is politically better and arguably a better solution anyway. Plus maybe I'm still not understanding the role and purpose of what proxy servers and environments have grown to be these days. My first attempt at a solution was to use WinInet with its various proxy capabilities to establish a connection over port 80 to my non-standard protocol server (which knows enough to recognize and answer a simple HTTP-looking GET request and answer it with a simple HTTP response page to get around some environments that employ initial packet sniffing (DPI)). I retrieved the actual SOCKET handle behind WinInet's HINTERNET request object and had hoped to use that in place of my software's existing SOCKET connection and hopefully not need to change much more on the client side. It initially seemed to be my solution but on further inspection it seems that the OS gets first-chance at the received data on this socket since when I get notified of events via the standard select(...) statement on the socket and query the size of the data available via ioctlsocket the call succeeds but returns 0 bytes available, the reads don't work and it goes downhill from there. Can someone tell me of a client-side library (commercial is fine) will let me get past these proxy server environments with as little user and IT staff help as possible? From what I read it has grown past SOCKS and I figure someone has to have solved this problem before me. Thanks for reading my long-winded question, Ripred
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 to the HTTP proxy on the proxy port; Send to the proxy: . CONNECT your.real.server:443 HTTP/1.1\r\n Host: your.real.server:443\r\n User-Agent: YourSoftware/1.234\r\n \r\n Then parse the proxy response, which will start with a HTTP status code, followed by HTTP headers, followed by a blank line. You'll then be talking with your destination (if the status code indicated success, anyway), and can start talking SSL. In many corporate environments you'll have to authenticate with the proxy - this is almost always HTTP Basic Authentication, which is pretty easy - again, see the RFCs.
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 FAR PASCAL convert (LPSTR filename); And this is the code I'm using in C# namespace Test{ public partial class Form1 : Form { [DllImport("convert.dll", SetLastError = true)] static extern Int32 convert([MarshalAs(UnmanagedType.LPStr)] string filename); private void button1_Click(object sender, EventArgs e) { // generate textfile string filename = "testfile.txt"; StreamWriter sw = new StreamWriter(filename); sw.WriteLine("line1"); sw.WriteLine("line2"); sw.Close(); // add checksum Int32 ret = 0; try { ret = convert(filename); Console.WriteLine("Result of DLL: {0}", ret.ToString()); } catch (Exception ex) { lbl.Text = ex.ToString(); } } }} Any ideas on how to proceed with this? Thanks a lot, Frank
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 certain conditions (which would cause my code to crash). Does anyone know if it's safe?
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_cast<T>(0)->Type? I've been using C++ for many years but have never seen 0 being used in a static_cast before. What is this code doing and is it safe? Background: If you derive from QGraphicsItem you are meant to declare an unique enum value called Type that and implement a virtual function called type that returns it, e.g.: class Item : public QGraphicsItem { public: enum { Type = MAGIC_NUMBER }; int type() const { return Type; } ... }; You can then do this: QGraphicsItem* item = new Item; ... Item* derivedItem = qgraphicsitem_cast<Item*>(item); This will probably help explain what that static_cast is trying to do.
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 value of Item::Type without actually using the value of the pointer. So this works, but is possibly undefined behavior (depending on your view of the standard, but IMO a bad idea anyway), because the code dereferences a NULL pointer with the pointer dereference operator (->). But I can't think why this is better over just Item::Type or the template T::Type - perhaps it's legacy code designed to work on old compilers with poor template support that couldn't work out what T::Type is supposed to mean. Still, the end result is code such as qgraphicsitem_cast<bool>(ptr) will fail at compile time because bool has no Type member enum. This is more reliable and cheaper than runtime checks, even if the code looks like a hack.
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#358094020874450#{a5dcbf10-6530-11d2-901f-00c04fb951ed}" Is there any way to to map DRIVE LETTER to my DEVICE PATH so please help me to map drive letter to DevicePath ) Thanks for any help.
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(VolumeDevicePath); VolumeDeviceNumber = DeviceIoControl(VolumeDevice, IOCTL_STORAGE_GET_DEVICE_NUMBER); if(VolumeDeviceNumber == DiskDeviceNumber) // volume (i.e. "G:") corresponding to VolumeDevicePath resides on disk (i.e. "XYZ USB Storage Device") corresponding to DiskDevicePath I'm not 100% sure (it's been a while), but I think that the Disk device (GUID_DEVINTERFACE_DISK) is a child of the USB device (GUID_DEVINTERFACE_USB_DEVICE). In any event, I think DiskDevicePath needs to be the path of the Disk device (not the USB device).
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 of some variables within the program? Or is it too late?
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 object which is lately persisted as it is in a DB. This works until in the TEXT there are just common ASCII characters. If we have i.e. chinese ones they get lost in the transcode operation. I've googled a lot seeking for a solution. It looks like with Xerces 3, the DOMWriter class should solve the problem. With Xerces 2.6 I'm trying the XMLTranscoder, but no success yet. Could anybody help? Edit It looks I was wrong and the DOMWriter class is already available in Xerces 2.6. I'm now trying a solution based on it.
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); DOMWriter* myWriter = ((DOMImplementationLS*)impl)->createDOMWriter(); XMLCh *strNodeValue = myWriter->writeToString(*node); XMLTransService::Codes resCode; XMLTranscoder* t = XMLPlatformUtils::fgTransService->makeNewTranscoderFor( "UTF-8", resCode, 16*1024); unsigned int charsEaten = 0; unsigned int charsReturned = 0; char bytesNodeValue[16*1024+4]; charsReturned = t->transcodeTo( strNodeValue, XMLString::stringLen(strNodeValue), (XMLByte*) bytesNodeValue, 16*1024, charsEaten, XMLTranscoder::UnRep_Throw); CBuffer xNodeText( bytesNodeValue, charsReturned); XMLString::release(&strNodeValue); myWriter->release(); delete t; return xNodeText; }
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 functions to accurately report time and memory usage.
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 to worry about that, the easiest way to trace memory usage in a cross-platform way is to use one of the many tracing malloc implementations. None of these tools come close to the ease of use of platform dependant tools like valgrind(+KCachgrind), or DTrace, all of which also have the advantage of being entirely external to the program.
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.push_back(c1); vector_of_parent.push_back(c2); // . . . Then in another method which has access to vector_of_parent, I tried void doSomething(Parent& some_child) { // wrapped in a try block somehow... Child1& c = dynamic_cast<Child1&> some_child; // do something if the cast is successful } void otherMethod() { doSomething(vector_of_parent.at(0)); // vector_of_parent.at(0) is a Child1 } Why is there a std:bad_cast when I call otherMethod()?
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 management, smart pointers). Appropriate container types to consider include std::vector<Parent*>, std::vector<std::tr1::shared_ptr<Parent> > and boost::ptr_vector<Parent>. I'd recommend against the std::vector<Parent*> unless you're very comfortable with manual memory management. Also, you need to use public inheritance instead of private, and the base class must have a virtual destructor. I assume you left these out for brevity though.
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 unable to run gst-inspect (or any other gstreamer applications) from the songbird sources and I figured I will settle for OSSBuild (as I was able to run gst-inspect from the compiled OSSBuild). When following the instructions for building a GST plugin (found here) through, cygwin will not recognize the OSSBuild and the build fails when running autogen, with the following error: checking for GST... no configure: error: You need to install or upgrade the GStreamer development packages on your system. On debian-based systems these are libgstreamer0.10-dev and libgstreamer-plugins-base0.10-dev. on RPM-based systems gstreamer0.10-devel, libgstreamer0.10-devel or similar. The minimum version required is 0.10.16. configure failed I could also not use MSYS or MinGW as they are unable to run autogen at all. I understand that cygwin should have it's own gstreamer development packages but I couldn't find how to install them. My question: How do I install the gstreamer packages in cygwin or how do I build using cygwin with the OSSBuild dependencies? In short, how do I get an environment where I can build a gstreamer plugin under windows?
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 want to be carrying ICU around with me.
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/html/ Tutorial http://cppcms.sourceforge.net/boost_locale/html/tutorial.html Download https://sourceforge.net/projects/cppcms/files/ It is not lightweight but it allows you handle Unicode correctly and it uses std::string as storage. If you expect to find Unicode-aware lightweight library to deal with strings, you'll not find such things, because Unicode is not lightweight. And even relatively "simple" stuff like upper-case, lower-case conversion or Unicode normalization require complex algorithms and Unicode data-base access. If you need an ability to iterate over Code points (that BTW are not characters) take a look on http://utfcpp.sourceforge.net/ Answer to comment: 1) Find file formats for files included by me std::string::find is perfectly fine for this. 2) Line break detection This is not a simple issue. Have you ever tried to find a line-break in Chinese/Japanese text? Probably not as space does not separate words. So line-break detection is hard job. (I don't think even glib does this correctly, I think only pango has something like that) And of course Boost.Locale does this and correctly. And if you need to do this for European languages only, just search for space or punctuation marks, so std::string::find is more then fine. 3) Character (or now, code point) counting Looking at utfcpp thx Characters are not code points, for example a Hebrew word Shalom -- "שָלוֹם" consists of 4 characters and 6 Unicode points, where two code points are used for vowels. Same for European languages where singe character and be represented with two code points, for example: "ü" can be represented as "u" and "¨" -- two code points. So if you are aware of these issues then utfcpp will be fine, otherwise you will not find anything simpler.
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 suggests), or abusing inheritance (avoid if possible): template <typename B, typename C> class Y : public X< std::vector<B>, B, C > {};
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::stack<myElement*> *mBats; } or @interface CarElement : NSObject { NSMutableArray *mBats; } Thanks,
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, you won't see any performance difference between Objective-C and C++ because the code doesn't have to scan the entire array but just the first element. Unless your array operations are very complex and the arrays very large e.g. 10K+ objects, you probably won't see any significant performance differences. My advice is to do a test run with some dummy data of the type you want to manipulate in the app. Load the arrays up past the max size you expect, loop a large number of manipulations then measure time and memory use. See if the performance gain of C++ justifies the extra dev time and complexity tax is worth the performance gain. Remember as well that premature optimization is the root of all evil. Don't spend time futzing to prevent a problem you might not even have. Default to the simplest solution unless you have good evidence to suspect it may not be sufficient.
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 (calling Java from C++). The key point is that CNI C++ methods can be invoked from Java (because these classes have a set of restrictions upon them to make them Java-compatible). And because the CNI class is only a (particular kind of) C++ class, you can also link it to other libraries just as you would link any C++ class. Most of the documentation describes how the Java conventions translate in a CNI C++ class.
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 technology but at the same time C# seems to be getting a lot of notoriety. Despite the newer technologies available there still remains c++ which is the staple for many popular vendors including google and facebook (hip hop) in building scalable and robust cross platform apps. Can anyone offer suggestions as to how I should be looking at this. Should I go Java, C# or C++). They all take time to master and I just want to choose a specialty. Thanks
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 actively developed language, due to the vendor position. It has however the largest ecosystem in terms of various libraries and third party products. Also cross-platform. Java jobs are plenty, but tend to pay less. C# language is being quite actively developed, to the point that sometimes annoys developers (who say they don't manage to keep up). Through this however you get a modern and powerful language including huge .NET class library, which makes developers very productive and on average very happy. It is however not cross-platform (except for Mono experiment) and at some point of your growth you may have to pay for licenses (Visual Studio IDE above Express edition and SQL Server (if you use it and if you exceed 4 GB database limit)). Jobs are usually fewer but pay more.
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: ostream &os; }; coutn() << "Hello " << "World" << "!"; In the end, I'm wondering if this coutn is actually better?
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 argument like -Wno-theNameOfTheWarning But I don't know the name of the warning. How can I find out the name of the option that disables this warning? I am not able to fix the warning, because it occurs in a header of an external library that can not be changed. It is in boost serialization (rx(s, count)): template<class Archive, class Container, class InputFunction, class R> inline void load_collection(Archive & ar, Container &s) { s.clear(); // retrieve number of elements collection_size_type count; unsigned int item_version; ar >> BOOST_SERIALIZATION_NVP(count); if(3 < ar.get_library_version()) ar >> BOOST_SERIALIZATION_NVP(item_version); else item_version = 0; R rx; rx(s, count); std::size_t c = count; InputFunction ifunc; while(c-- > 0){ ifunc(ar, s, item_version); } } I have already tried #pragma GCC system_header but this had no effect. Using -isystem instead of -I also does not work. The general question remains is: I know the text of the warning message. But I do not know the correlation to the gcc warning options.
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 no way to actually fix the warning, hopefully you can manage to disable the warning for a minimal amount of compilation, so that if you make a similar mistake in your own code, you'll be warned. Edit: This appears to be -Wconversion. (Found by poking in the source - you can just grep for some of the warning text, and find the call to warning( OPT_W_conversion, ....)
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() { for (iterator it=m_Callbacks.begin(); it!=m_Callbacks.end(); it++) { (*it)->NodulesChanged(); } } }; I'm considering changing this to use boost's signals and slots as it would be beneficial to reduce the likelihood of dangling pointers when the callee gets deleted, among other things. However, as it stands boost's signals seems more oriented towards dealing with function objects. What would be the best way of adapting my code to still use the callback interface but use signals and slots to deal with the connection and notification aspects?
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 /////////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- template <class CallbackType> class CallbackInvoker { public: virtual ~CallbackInvoker() {} virtual void operator()(CallbackType* callback) const {}; }; //----------------------------------------------------------------------------- template <class CallbackType, class Binding> class BoundInvoker : public CallbackInvoker<CallbackType> { public: BoundInvoker(const Binding& binding) : binding_(binding) {} void operator()(CallbackType* callback) const {binding_(callback);} private: Binding binding_; }; //----------------------------------------------------------------------------- template <class CallbackType> class CallbackSlot { public: CallbackSlot(CallbackType* callback) : callback_(callback) {} void operator()(const CallbackInvoker<CallbackType>& invoker) {invoker(callback_);} private: CallbackType* callback_; }; //----------------------------------------------------------------------------- template <class CallbackType> class Subject { public: virtual ~Subject() {} boost::signals::connection Connect(CallbackType* callback) {return signal_.connect(CallbackSlot<CallbackType>(callback));} protected: template <class Binding> void Signal(const Binding& binding) { signal_(BoundInvoker<CallbackType,Binding>(binding)); } private: boost::signal<void (const CallbackInvoker<CallbackType>&)> signal_; }; /////////////////////////////////////////////////////////////////////////////// // THIS PART SPECIFIC TO ONE SUBJECT /////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------ class MyCallback { public: virtual ~MyCallback() {} virtual void NodulesChanged() =0; virtual void TurkiesTwisted(int arg) =0; }; //----------------------------------------------------------------------------- class FooCallback : public MyCallback { public: virtual ~FooCallback() {} void NodulesChanged() {std::cout << "Foo nodules changed\n";} void TurkiesTwisted(int arg) {std::cout << "Foo " << arg << " turkies twisted\n";} }; //----------------------------------------------------------------------------- class BarCallback : public MyCallback { public: virtual ~BarCallback() {} void NodulesChanged() {std::cout << "Bar nodules changed\n";} void TurkiesTwisted(int arg) {std::cout << "Bar " << arg << " turkies twisted\n";} }; //----------------------------------------------------------------------------- class MySubject : public Subject<MyCallback> { public: void OnNoduleChanged() {this->Signal(boost::bind(&MyCallback::NodulesChanged, _1));} void OnTurkiedTwisted(int arg) {this->Signal(boost::bind(&MyCallback::TurkiesTwisted, _1, arg));} }; /////////////////////////////////////////////////////////////////////////////// // CLIENT CODE /////////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- int main() { MySubject subject; FooCallback fooCb; BarCallback barCb; subject.Connect(&fooCb); subject.Connect(&barCb); subject.OnNoduleChanged(); subject.OnTurkiedTwisted(42); } Hooray for boost::bind! :-)
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 it BaseConfigurationPage) with these two slots as virtual pure methods ? (Every possible configuration page will always have these two methods, so I would say "yes") Before I do the heavy change in my code (if I have to) : does Qt support virtual pure slots ? Is there anything I should be aware of ? Here is a code example describing everything: class BaseConfigurationPage : public QWidget { // Some constructor and other methods, irrelevant here. public slots: virtual void loadSettings() = 0; virtual void saveSettings() = 0; }; class GeneralConfigurationPage : public BaseConfigurationPage { // Some constructor and other methods, irrelevant here. public slots: void loadSettings(); void saveSettings(); };
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 the subclass, you actuallly don't need to mark the overriden methods as slots. First, they're already implemented as slots in the base class. Second, you're just creating more work for the MOC and compiler since you're adding a (tiny) bit more code. Trivial, but whatever. So, go for it..
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 << " -> " << i->second << std::endl; return 0; } ...fails to compile. bidi.cxx: In function ‘int main()’: bidi.cxx:13: error: no match for ‘operator--’ in ‘--i’ According to Boost's own documentation: iterator, const_iterator are of at least the forward category. It would appear that that's all they are. Why? What technical restriction does a hash-map impose that prevents iterators from being bidirectional? (gcc version 4.1.2, Boost versions 1.40.0 and 1.43.0.)
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 iterator gives you is entirely arbitrary. What would traversing a fixed but arbitrary order backwards give you? Normally, one would access an unordered_map on an element-by-element basis, or traverse the whole map. I've never done otherwise in Perl, myself. To do this, a forward iterator is necessary, and therefore there is one in there, and Boost guarantees it. To have bidirectional iterators, it would likely be necessary to include an additional pointer in each entry, which increases memory use and processing time. I'm not coming up with a good, plausible, use case for bidirectional iterators here. If you can, you can ask the Boost maintainers to consider it, although you're almost certainly too late for C++0x.
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 32 and the third dimension has 16 elements.
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(16, 0.0))); I would remark that this allocate a fair lot of objects (32*32*16). Would a single vector work ? std::vector<double> values(32*32*16, 0.0) That would be 32*32*16-1 less new.
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 2008 C++
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 the texture width is 7, the image is usually stored as 8*4 bytes instead of 7*4 bytes because the memory can be accessed faster if the data is DWORD-aligned. So, in order to read pixel [x, y] you would have to read uint8_t *pixels = rect.pBits; uint32_t *mypixel = (uint32_t*)&pixels[rect.Pitch*y + 4*x]; where 4 is the size of a pixel. *myPixel would be the content of the pixel in my example.
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 texName; bool itt; void makeCheckImage(void) { Bitmap *b = new Bitmap(L"c:/boo.png"); int i, j, c; Color cul; for (i = 0; i < checkImageHeight; i++) { for (j = 0; j < checkImageWidth; j++) { b->GetPixel(j,i,&cul); checkImage[i][j][0] = (GLubyte) cul.GetR(); checkImage[i][j][1] = (GLubyte) cul.GetG(); checkImage[i][j][2] = (GLubyte) cul.GetB(); checkImage[i][j][3] = (GLubyte) cul.GetA(); } } delete(b); } work without making a multidimensional array. width = 512, height = 1024....
[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 implementation of ostream and, of course, is now irretrievably broken with VS2008. It would be reasonable to accumulate all the output until program termination time and then dump it to a file. I got part of the way home by using freopen(), setvbuf(), and ios::sync_with_stdio(), but to my dismay, the internal library does not treat its buffer as a ring buffer; instead when it flushes to the output device it restarts at the beginning, so every flush wipes out all my accumulated output. Converting to a more standard logging function is not desirable, as there are over 1600 usages of "std::cout << " scattered throughout almost 60 files. I have considered overriding ostream's operator<< function, but I'm not sure if that will cover me, since there are global operator<< functions that can't be overridden. (Or can they?) Any ideas on how to accomplish this?
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 teeing stream buffer you can get an inspiration from this page.
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 Thanks
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.name; } }; // sort by age std::sort(students.begin(), students.end(), by_age()); // sort by name std::sort(students.begin(), students.end(), by_name()); Starting with C++11, you can use a lambda expression to do the comparison "in place", something like this: // sort by name: std::sort(students.begin(), students.end(), [](student const &a, student const &b) { return a.name < b.name; }); // sort by age: std::sort(students.begin(), students.end(), [](student const &a, student const &b) { return a.age < b.age; });
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> using namespace std; int main(int argc, char *argv[]) { SDL_Surface *hello; SDL_Surface *screen; SDL_Init(SDL_INIT_EVERYTHING); screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE); hello = SDL_LoadBMP("hello.bmp"); SDL_BlitSurface(hello, NULL, screen, NULL); SDL_Flip(screen); SDL_Delay(2000); SDL_FreeSurface(hello); SDL_Quit(); return 0; }
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 params (...)*/, callback, obj2); See that the *AnyClass is going to be cast to gpointer* (void**). In fact, this is working now. The callback prototype in GTK documentation is "gpointer data" and not "gpointer *data" as shown in code, what I want to know is: how this can work ? Is this safe ?
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 started with....IFF alignment requirements of T1* and T2* are the same. In other words, it will work on most implementations. The cast to/from void* is guaranteed but I don't know that there are any requirements for a void**. Doing a reinterpret_cast is always kind of risky. You have to get the T1 exactly right on both sides and the compiler has no way of helping you if you get it wrong. For example, if you cast from class T5, which is a subclass of T1, and then on the other side cast to a T1*...you could be totally screwed. The static_cast would have accounted for this I believe but a reinterpret_cast will not. It could work just fine until someone uses multiple inheritance on T5 for whatever reason. You're not gaining anything by adding the * to the hiding type. You should consider not doing it this way. NOTE: my answer is regarding the C++ language. You tagged your question as both so you're bound to get answers for both and they're going to be very different.
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 need a mechanism to convert a vector of one type (e.g. vector3d<float>) to a vector of the other type (e.g. btVector3). Unfortunately I can make no assumptions on how the classes/structs are laid out, so a simple reinterpret_cast probably won't do. So the question is: Is there some sort of 'static'/non-member casting method to achieve basically this: vector3d<float> operator vector3d<float>(btVector3 vector) { // convert and return } btVector3 operator btVector3(vector3d<float> vector) { // convert and return } Right now this won't compile since casting operators need to be member methods. (error C2801: 'operator foo' must be a non-static member)
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; // ...populate... btVector3 two(btVectorFrom3d(one)); // ... vector3d<float> three(vector3dFromBt(two)); }
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 week I did some complex solutions with templates. But in reality one can use already predefined valarray for my tasks. Here is the code snippet maybe one can find it useful: double dr=Rc/(double)Nbins, r; sigma.resize(Nbins); rr=sigma; valarray<double> vz(&data.vz[0], data.vz.size()); double mvel=vz.sum()/(double)vz.size(); for(size_t i=0l;i<Nbins;i++) { r=dr*i; valarray<bool> ids = (dist < r+dr) && (dist > r);//The magic valarray<bool> if(ids.max()) { valarray<double> d=vz[ids];//we can use indirect operation. d-=mvel; d=pow(d,2.0); sigma[i]= sqrt(d.sum()/(double)d.size()); rr[i]=r; cout<<i<<") "<<r<<" "<<sigma[i]<<endl; } }
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_x3() || bool_x4() && bool_x5())); If you're tempted to write a "where" function then you apparently want to do this more than once with a different set of bool_xxx functions. Even if you know that you want a certain type of composition now, you may as well make it as universal as possible. This is how I'd do it. Edit: Based on this comment: @Jerry: For example I need to know: id=where(v < 10.0 && v>1.0); and somewhere later I would like to know: id=where(v < fun(v)); you may be better off with boost::lambda: namespace l = boost::lambda; std::find_if(vect.begin(), vect.end(), l::_1 < 10.0 && l::_1 > 1.0); std::find_if(vect.begin(), vect.end(), l::_1 < l::bind(fun, l::_1)); Or, if you hate lambda or aren't allowed to use it...or just want a very slightly nicer syntax (but inability to use functions directly) then just make your own placeholder type and override it to return bool_xxx functors on operators <, >, etc... Edit2: Here's an untested where that returns a vector of iterators to all objects matching: template < typename ForwardIter, typename Predicate > std::vector<ForwardIter> where(ForwardIter beg, ForwardIter end, Predicate pred) { ForwardIter fit = std::find_if(beg,end,pred); if (fit == end) return std::vector<ForwardIter>(); ForwardIter nit = fit; ++nit; std::vector<ForwardIter> collection = where(nit,end,pred); collection.push_front(fit); return collection; } It's recursive and could be slow on some implementations but there's one way to do it.
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_VAL_THREE }; enum BVal { B_VAL_ONE, B_VAL_TWO, B_VAL_THREE }; class Base { //... virtual AVal getAVal() const = 0; virtual BVal getBVal() const = 0; //... }; class One : public Base { //... AVal getAVal() const { return A_VAL_ONE }; BVal getBVal() const { return B_VAL_ONE }; //... }; class Two : public Base { //... AVal getAVal() const { return A_VAL_TWO }; BVal getBVal() const { return B_VAL_TWO }; //... }; etc. Is this a common way of doing things? If performance is an important consideration, would I be better off pulling the attributes out into an external structure, e.g.: struct Vals { AVal a_val; VBal b_val; }; storing a Vals* in each instance, and rewriting Base as follows? class Base { //... public: AVal getAVal() const { return _vals->a_val; }; BVal getBVal() const { return _vals->b_val; }; //... private: Vals* _vals; }; Is the extra dereference essentially the same as the vtable lookup? What is the established idiom for this type of situation? Are both of these solutions dumb? Any insights are greatly appreciated
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. That being said, what problem are you trying to solve? Sometimes class ids like this are useful but sometimes a different interface abstraction can accomplish the same thing without having have such an interface at all.
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 = new Bitmap(filename); if(b == NULL) { return 0; } UINT w,h; w = b->GetWidth(); h = b->GetHeight(); Rect *r = new Rect(0,0,w,h); BitmapData *lockdat; b->LockBits(r,ImageLockModeRead,PixelFormatDontCare,lockdat); delete(r); if(w == 0 && h == 0) { return 0; } Color c; std::vector<GLubyte> pdata(w * h * 4,0.0); for (unsigned int i = 0; i < h; i++) { for (unsigned int j = 0; j < w; j++) { b->GetPixel(j,i,&c); pdata[i * 4 * w + j * 4 + 0] = (GLubyte) c.GetR(); pdata[i * 4 * w + j * 4 + 1] = (GLubyte) c.GetG(); pdata[i * 4 * w + j * 4 + 2] = (GLubyte) c.GetB(); pdata[i * 4 * w + j * 4 + 3] = (GLubyte) c.GetA(); } } delete(b); return CreateTexture(pdata,w,h); How do I use lockdat to do the equivalent of getpixel? Thanks
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, red, green and blue. And the stride will be equal to the width of the bitmap. Making it likely that a simple memcpy() will get the job done. Beware the bitmaps are stored upside-down.
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 problem is that all access to these objects is via a base QGraphicsItem pointer, so the serialization code I have is horrible: QGraphicsScene* scene = new QGraphicsScene; scene->addRect(QRectF(0, 0, 100, 100)); scene->addLine(QLineF(0, 0, 100, 100)); ... QList<QGraphicsItem*> list = scene->items(); foreach (QGraphicsItem* item, items) { if (item->type() == QGraphicsRectItem::Type) { QGraphicsRectItem* rect = qgraphicsitem_cast<QGraphicsRectItem*>(item); // Access QGraphicsRectItem members here } else if (item->type() == QGraphicsLineItem::Type) { QGraphicsLineItem* line = qgraphicsitem_cast<QGraphicsLineItem*>(item); // Access QGraphicsLineItem members here } ... } This is not good code IMHO. So, instead I could create an ABC class like this: class Item { public: virtual void serialize(QDataStream& strm, int version) = 0; }; class Rect : public QGraphicsRectItem, public Item { public: void serialize(QDataStream& strm, int version) { // Serialize this object } ... }; I can then add Rect objects using QGraphicsScene::addItem(new Rect(,,,)); But this doesn't really help me as the following will crash: QList<QGraphicsItem*> list = scene->items(); foreach (QGraphicsItem* item, items) { Item* myitem = reinterpret_class<Item*>(item); myitem->serialize(...) // FAIL } Any way I can make this work?
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<QGraphicsItem*>(r); QGraphicsRectItem *qr = reinterpret_cast<QGraphicsRectItem*>(r); Item *i = reinterpret_cast<Item*>(r); qDebug("r = %p, qi = %p, qr = %p, i = %p", r, qi, qr, i); You should see that r == qi, r == qr, but r != i. If you think about how an object that multiply inherits is represented in memory, the first base class is first in memory, the second base class is second, and so forth. So the pointer to the second base class will be offset by [approximately] the sizeof the first base class. So to fix your code, I think you need to do something like: QList<QGraphicsItem*> list = scene->items(); foreach (QGraphicsItem* item, items) { Rect* myrect = reinterpret_class<Rect*>(item); // needed to figure out the offset to the Item part Item* myitem = reinterpret_class<Item*>(myrect); myitem->serialize(...); } This is one of many reasons, I like to avoid multiple inheritance whenever possible. I strongly recommend separating you model data, as previously recommended.
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 allows the type of an object to be determined at run time. So, does this sample code tell us that a function that returns void is of **type void**. I mean a function is a method and has no type. Correct?
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 refers to type void. void, BTW, is not an object type. Function do have types. If you want to apply typeid to the function itself, the syntax would be typeid(foo). The function-to-pointer conversion is not applied to the argument of typeid, which means that you should get a result that refers to function type itself. Meanwhile, typeid(&foo) will give you a function pointer type id, which is different from typeid(foo).
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 appropriately. For example: 1>- add -D_WIN32_WINNT=0x0501 to the compiler command line; or 1>- add _WIN32_WINNT=0x0501 to your project's Preprocessor Definitions.
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 were still getting that error and provided the contents of your preprocessor settings, WIN32;_DEBUG;_CONSOLE;_WIN32_WINNT = 0x0501. I think you can solve this if you change _WIN32_WINNT = 0x0501 to _WIN32_WINNT=0x0501. When I tried the version with spaces, it did not eliminate the error, but removing the spaces did.
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 testClass { private: int health; public: testClass(); ~testClass(); int getHealth(); void setHealth(int inH); }; #endif // TEST_H_INCLUDED test.cpp: #include "test.h" testClass::testClass() { health = 100; } testClass::~testClass() {} int testClass::getHealth() { return(health); } void testClass::setHealth(int inH) { health = inH; } What I'm trying to do is pretty simple, but the way the header files work just makes no sense to me at all. Code blocks returns the following on build: obj\Debug\main.o(.text+0x131)||In function main':| *voip*\test\main.cpp |6|undefined reference totestClass::testClass()'| obj\Debug\main.o(.text+0x13c):voip\test\main.cpp|7|undefined reference to `testClass::~testClass()'| ||=== Build finished: 2 errors, 0 warnings ===| I'd appreciate any help. Or if you have a decent tutorial for it, that would be fine too (most of the tutorials I've googled haven't helped)
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 Release and Debug checkboxes are checked. Then Build->Rebuild. EDIT: Here's a tip to help you see what the IDE is doing under the hood when compiling. Go to Settings -> Compiler and Debugger -> Global Compiler Settings -> Other settings and select Full command line in the Compiler logging drop box. Now, whenever you build, the gcc compiler commands will be logged in the Build Log. Whenever someone on StackOverflow asks you for the gcc command line you used, you can copy and paste what's in the Build Log.
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 the vector, sps->pwsz is the same. Is this because I'm passing a pointer to memory allocated in a loop, which is destructed after each iteration, and then refilling that same memory on the next iteration?
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 that invalid memory address. After your while loop all of your smart pointers point to that same invalid already freed address. The address was re-used and freed on each iteration.
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 can I get the same speed+flexibility that I can get with this code?
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)