question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
1,790,291
1,790,337
Using Boost on Windows (Visual Studio)
I want to get started using Boost. I'm programming a C++ program in Visual Studio (obviously on a Windows machine). Boost's Getting Started Guide says: The easiest way to get a copy of Boost is to use an installer. The Boost website version of this Getting Started guide will have undated information on installers as they become available, or see Boost downloads or the installer provided by BoostPro Computing. We especially recommend using an installer if you use Microsoft Visual Studio, because the installer can download and install precompiled library binaries, saving you the trouble of building them yourself. I'm a little unsure if I want to follow this advice, or just download and build everything myself. Potential problems that I see with an installer are: Things are no longer self-contained (i.e. every team member has to install Boost, then configure Visual Studio to recognize it). I can't keep Boost under source control (I would ideally like it to be soure files in my source control like everything else). (Edit: Judging by the comments, it looks like boost is kinda large (as in 5 GB!), so obviously I'd need to keep only parts of it under source control). So my question is, am I just being paranoid and should go the installer route, or am I correct and should build it myself? If anyone has any experience working with Boost and Visual Studio, I'd appreciate if they could share their views on this (and if it should be to build it myself, any tips would also be appreciated, for example should I only copy every file that I actually use? etc.). Note: A few similar questions on StackOverflow, but which didn't ask this explicitly, make me think that I shouldn't use the installer, which is why I'm asking it explicitly here. For reference, these are the questions: Boost linking, Visual Studio & version control Including Relevant Boost Libraries with C++ Source (Using Visual Studio)
A good way to make sure everyone has everything configured properly is to use svn externals. You can create something like /trunk/boost1.35 and then you can point to that with an svn external. That way as new versions of boost come out, you can just repoint your svn external to /trunk/boost1.40 In your repository, your svn external points to that svn folder within your repository. Example /depends/boost We personally keep the boost header files under source control as described but keep the libs as a zip that we require everyone to download. We have an environment variable something like the following BOOST_LIB and we point that to the current boost library directory.
1,790,704
1,790,720
Difference between [square brackets] and *asterisk
If you write a C++ function like void readEmStar( int *arrayOfInt ) { } vs a C++ function like: void readEmSquare( int arrayOfInt[] ) { } What is the difference between using [square brackets] vs *asterisk, and does anyone have a style guide as to which is preferrable, assuming they are equivalent to the compiler? For completeness, an example void readEmStar( int *arrayOfInt, int len ) { for( int i = 0 ; i < len; i++ ) printf( "%d ", arrayOfInt[i] ) ; puts(""); } void readEmSquare( int arrayOfInt[], int len ) { for( int i = 0 ; i < len; i++ ) printf( "%d ", arrayOfInt[i] ) ; puts(""); } int main() { int r[] = { 2, 5, 8, 0, 22, 5 } ; readEmStar( r, 6 ) ; readEmSquare( r, 6 ) ; }
When you use the type char x[] instead of char *x without initialization, you can consider them the same. You cannot declare a new type as char x[] without initialization, but you can accept them as parameters to functions. In which case they are the same as pointers. When you use the type char x[] instead of char *x with initialization, they are completely 100% different. Example of how char x[] is different from char *x: char sz[] = "hello"; char *p = "hello"; sz is actually an array, not a pointer. assert(sizeof(sz) == 6); assert(sizeof(sz) != sizeof(char*)); assert(sizeof(p) == sizeof(char*)); Example of how char x[] is the same as char *x: void test1(char *p) { assert(sizeof(p) == sizeof(char*)); } void test2(char p[]) { assert(sizeof(p) == sizeof(char*)); } Coding style for passing to functions: It really doesn't matter which one you do. Some people prefer char x[] because it is clear that you want an array passed in, and not the address of a single element. Usually this is already clear though because you would have another parameter for the length of the array. Further reading: Please see this post entitled Arrays are not the same as pointers!
1,790,932
1,790,952
Get Directory from User
I'm looking for a function to get a directory path from the user; I need to solicit a place to put things. I tried using GetOpenFileName() with .dir as a filter but no joy. I found something called GetDirectoryViaBrowse() that sounds like it might do what I want but it's part of some wizard making package and my Visual Studio knows nothing about it. I'd like some simple non .NET widget. Is there such a thing?
You are looking for the Win32 Shell API: SHBrowseForFolder
1,790,949
1,790,972
external vs internal linkage and performance
let's say i have 3 functions inside a class : class Foo { inline void FooInline() { /* bla bla */ } static void fooStatic(); void foo(); }; as i understand the last two have external linkage while the first have internal. i want to know which function will be the fastest to call to , and what's the tradeoff. thanks
No, all three have external linkage. Member functions of a non-local class always have external linkage in C++. Moreover, inline has no effect on linkage, even if it is a non-member function. Linkage has no effect on efficiency. Inlining might have, but it depends on too many variables.
1,791,447
1,795,071
Copying between VARIANT and _variant_t
I'm fairly certain that I can safely do: void funcA(VARIANT &V,_variant_t &vt) { vt = V; } But what about the other way around: void funcB(VARIANT &V,_variant_t &vt) { V = vt; } I've been seeing some REALLY weird behaviour in my app which I put down to COM-related threading issues. But then I got wondering if I was screwing up memory using variants wrongly. In funcB, the VARIANT V is part of a safe-array being prepared for a COM call. With my V=vt line, am I doing a shallow copy which will break things when the same variant gets deallocated twice? I really like _variant_t and avoiding all the ::VariantXXX methods, is there a neat way to use _variant_t in funcB to automate the copying?
First of all, yes, by using the assignment operator the way you do in funcB() you invoke shallow copying only (you might want to look into oaidl.h to see the VARIANT definition - it has no user-defined assignment operator and therefore shallow copying is done by the compiler). This gets you into undefined behaviour if the other variant you copied from is cleared before you access the shallow copy (for example, if the variant type was VT_UNKNOWN the object pointed to could simply be destroyed after setting the reference count to 0 by calling the IUnknown::Release()). _variant_t will not help you much since it has no methods for copying to another object - see comutil.h for class definition - it only copies from another object to itself. The easiest way would be to use VariantCopy(). Not sure if the safearray will be initialized when you deal with it. If it is initialized with each element having VT_EMPTY you can just call VariantCopy(). Otherwise first call VariantInit() on the destination to initialize the destination. Calling VariantCopy() for a destination containing random uninitialized data can lead to undefined behaviour.
1,791,578
1,791,609
How do I convert a char string to a wchar_t string?
I have a string in char* format and would like to convert it to wchar_t*, to pass to a Windows function.
Does this little function help? #include <cstdlib> int mbstowcs(wchar_t *out, const char *in, size_t size); Also see the C++ reference
1,791,783
1,794,458
Assembler and C++ relation
Is there any tutorial or explanation anywhere on how C++ objects translate into assembler instructions moving data between registers... I don't really understand how we are manipulating object in higher level languages where in Assembler you're essentially moving data between registers? Plus doing some basic operations on them.
Disclaimer: I will use IA-32 assembly for samples. Typically, each object is a structure residing block of memory allocated either on heap (via new call) or on stacK (basically, by moving esp to reserve memory for it). After memory is allocated, pointer is passed to object constructor for initialization (note that ctor can be inlined, this way no call is made). Usually, each object having virtual methods has a pointer a table of virtual methods (usually called VMT or vtable which stores pointers to functions. When you are calling virtual method, address of this method is got and it is called. Code looks like this mov ecx, [this] mov ebx, vtable push [arg2] push [arg1] call [ebx + OFFSET_foo] ; this->foo(arg1, arg2); Note that in this sample I've shown that this is passed via ecx and args are passed via stack in right-to-left order. This is thiscall convention, used in VC++ by default, e.g. Other compilers may employ other conventions, as it is shown in article linked. For non-virtual calls no need for table lookup. So code looks like mov ecx, [this] push [args] push [arg1] call bar ; this->bar(arg1, arg2) This is why non-virtual methods can be executed a bit faster - its address is well known, so compiler can start decoding their code before encountering call opcode. In some calling conventions (e.g. fastcall) arguments are passed via registers which can be faster in some cases. In most calling conventions result iss returned via eax register if it fits this registers, via FPU stack, if this is floating point or via stack otherwise. If you want to learn more about translating C++ code to assembly, I'd recommend to try to make your compiler generate assembly listing during compilation (usually -S key; it can be set in VC++ project settings as well); try to disassemble code e.g. using excellent IDA disassembler. There's free version of it. It helps a lot by providing symbolic names for local variables, recognizing library functions etc. Good luck!
1,792,147
1,792,176
Comparing character arrays and string literals in C++ without cstring
In my programming class we currently have a project that requires us to take arguments into the program. I then need to be able to check one of the arguments to see which value was passed to the program so that I can choose the appropriate behavior for the program to follow. In a previous homework assignment I did this with the strcmp function included in the cstring library using the following code: int main(int argc, char *argv[]) { if (strcmp(argv[1], "yes") == 0) { // do this code } else if (strcmp(argv[1], "no") == 0) { // do this code } } However, for some reason we're not allowed to use the cstring library in this project. How else can I do this?
Try this: if (argv[1] == std::string("yes")) { stuff } If the intent of the exercise is to teach how string comparisons work, then implement a for loop like other answers suggest. However, in C++ you are not supposed to use strcmp - there is a string class for a reason.
1,792,253
1,792,410
Default template parameters with forward declaration
Is it possible to forward declare a class that uses default arguments without specifying or knowing those arguments? For example, I would like to declare a boost::ptr_list< TYPE > in a Traits class without dragging the entire Boost library into every file that includes the traits. I would like to declare namespace boost { template<class T> class ptr_list< T >; }, but that doesn't work because it doesn't exactly match the true class declaration: template < class T, class CloneAllocator = heap_clone_allocator, class Allocator = std::allocator<void*> > class ptr_list { ... }; Are my options only to live with it or to specify boost::ptr_list< TYPE, boost::heap_clone_allocator, std::allocator<void*> in my traits class? (If I use the latter, I'll also have to forward declare boost::heap_clone_allocator and include <memory>, I suppose.) I've looked through Stroustrup's book, SO, and the rest of the internet and haven't found a solution. Usually people are concerned about not including STL, and the solution is "just include the STL headers." However, Boost is a much more massive and compiler-intensive library, so I'd prefer to leave it out unless I absolutely have to.
Any compilation unit that uses your facility that forward-declares boost stuff will need to include the boost headers anyway, except in the case that you have certain programs that won't actually use the boost part of your facility. It's true that by forward-declaring, you can avoid including the boost headers for such programs. But you'll have to manually include the boost headers (or have an #ifdef) for those programs that actually use the boost part. Keep in mind that more default template parameters could be added in a future Boost release. I'd advise against this route. What I would consider, if your goal is to speed compile times, is to use a #define to indicate whether the code using that boost library should be disabled. This way you avoid the forward declaration hassle.
1,792,275
1,792,330
Difference between WinMain and wWinMain
The only difference is that Winmain takes char* for lpCmdLine parameter, while wWinMain takes wchar_t*. On Windows XP, if an application entry is WinMain, does Windows convert the command line from Unicode to Ansi and pass to the application? If the command line parameter must be in Unicode (for example, Unicode file name, conversion will cause some characters missing), does that mean that I must use wWinMain as the entry function?
On Windows XP, if an application entry is WinMain, does Windows convert the command line from Unicode to Ansi and pass to the application? Yes. If the command line parameter must be in Unicode (for example, Unicode file name, conversion will cause some characters missing), does that mean that I must use wWinMain as the entry function? Yes, you should, if you want to correctly handle Unicode arguments to your program. The documentation to WinMain() on MSDN also agrees. You can, however, also use GetCommandLineW to retrieve the command line specifically in Unicode.
1,792,360
1,793,767
What are the limits of Python?
I spent a few days reading about C++ and Python and I found that Python is so much simpler and easy to learn. So I wonder does it really worth spending time learning it? Or should I invest that time learning C++ instead? What can C++ do and Python can't ?
Some Python limits : - Python is slow. It can be improved in many ways (see other answers) but the bare bone cPython is 100 times slower that C/C++. This problem is getter more and more mitigated. With Numpy, Pypy and asyncio, most performance problems are not covered, and only very specific use cases are a bottleneck in Python anymore. - Python is opened to anything. It's really hard to protect / obfuscate / limit Python code. - Python is not hype. Unlike Ruby, there is no "cool wave" around Python, and it's still much harder to find a experienced Python coder, than, let's say, a Java or a PHP pro. - After using Python, a lot of languages seems to be a pain to use. You'd think it's good, but believe me, not always. When you have to go Javascript after a Python project, your eyes are in tears for at least 3 days. Really hard to get started. - It's harder to find web hosting than for popular solutions, such as PHP. - As a dynamic language, you don't have the very handy refactoring tools you could get with Java and Eclipse or C# and VS. - For the same reason, you can't rely on type checking as a safety net. This is why pythonistas tend to follow best practice and write unit tests more often than others. - It seems I just can't find an IDE with a decent code completion. PyDev, Gedit, Komodo, SPE, etc. just don't do it as good as it could be. With Python 3 types hints and tools like PyCharm or Sublime Text+Anaconda, the situation has changed a lot. - The best docs are still in English only. Some people don't deal well with it. - You have to get use to the syntax. Not only you get spaces and line breaks instead of bracets, but you can forget about long lambdas, --i, and ternary operation. Now, to me, these are not reasons to not learn a tool that will make you produce more while having more fun. But maybe it's just me :-) Honestly, given that : C++ much harder to learn; You can do pretty much any thing you want with Python; You will get quicker result with Python in your projects. Unless you have professional issues involving C++, you'd better learn Python first, it's more motivating. You still can learn C++ later, it's a useful language for system programming, embedded devices and such. Don't try to learn both at the same times, multitasking rarely ends well.
1,792,380
1,792,431
How I can use mysql in C++?
I have searched a lot, all I found is a "mysql++" but I don't know how to install it. I don't have knowledge about libraries in C++!
Searching google for "c++ mysql tutorial" brings back the following Developing Database Applications Using MySQL Connector/C++ and A Tiny MySQL++ Tutorial; C++ and MySQL; MySQL++ Example Which in turn links to... Installing MySQL++; How to install MySQL++ on Linux-CentOS And looking through the first article I found this Installing MySQL Connector/C++ from Source They all seem straight forward enough. Although installation processes vary slightly dependant on your operating system.
1,792,520
1,792,766
slightly weird C++ code
Sorry if this is simple, my C++ is rusty. What is this doing? There is no assignment or function call as far as I can see. This code pattern is repeated many times in some code I inherited. If it matters it's embedded code. *(volatile UINT16 *)&someVar->something; edit: continuing from there, does the following additional code confirm Heaths suspicions? (exactly from code, including the repetition, except the names have been changed to protect the innocent) if (!WaitForNotBusy(50)) return ERROR_CODE_X; *(volatile UINT16 *)& someVar->something; if (!WaitForNotBusy(50)) return ERROR_CODE_X; *(volatile UINT16 *)& someVar->something; x = SomeData;
This is a fairly common idiom in embedded programming (though it should be encapsulated in a set of functions or macros) where a device register needs to be accessed. In many architectures, device registers are mapped to a memory address and are accessed like any other variable (though at a fixed address - either pointers can be used or the linker or a compiler extension can help with fixing the address). However, if the C compiler doesn't see a side effect to a variable access it can optimize it away - unless the variable (or the pointer used to access the variable) is marked as volatile. So the expression; *(volatile UINT16 *)&someVar->something; will issue a 16-bit read at some offset (provided by the something structure element's offset) from the address stored in the someVar pointer. This read will occur and cannot be optimized away by the compiler due to the volatile keyword. Note that some device registers perform some functionality even if they are simply read - even if the data read isn't otherwise used. This is quite common with status registers, where an error condition might be cleared after the read of the register that indicates the error state in a particular bit. This is probably one of the more common reasons for the use of the volatile keyword.
1,792,521
1,792,565
What does this warning message mean?
Product.cpp:34: warning: the address of ‘QTextStream& endl(QTextStream&)’, will always evaluate as ‘true’ Product.cpp: In member function ‘void Product::setProductToSold()’: Product.cpp:45: warning: the address of ‘QTextStream& endl(QTextStream&)’, will always evaluate as ‘true’ #include <string> #include <iostream> #include <time.h> using std::string; using std::cout; #include "Product.h" Product::Product() { seller = ""; itemName = ""; price = 0.00; min = 0.00; buyingPrice = 0.00; time = 0; description = ""; highestBidder = "None"; currentBid = 0.00; timer = new QTimer( this ); connect( timer, SIGNAL(timeout()), this, SLOT(setProductToSold()) ); } void Product::startTimer() { Line 34: cout << " Timer Started " << endl; timer->start( 2000, TRUE ); // 2 seconds single-shot timer } void Product::setHandler(Handler *h) { handler = h; } void Product::setProductToSold() { Line 45: cout << " Item auction over" << endl; } My Product.h:: #include <string> #include <qobject.h> #include <qtimer.h> #include <qgl.h> #include "HandleTCPClient.h" class Handler; //Define ourselves a product class class Product : public QObject { Q_OBJECT public: Product(); QTimer *timer; string seller, itemName, description, highestBidder; double price, min, buyingPrice, currentBid; int time; bool isSold; Handler *handler; void setHandler(Handler *h); void startTimer(); public slots: void setProductToSold(); }; #endif Thanks :)
Are you (or Qt) redefining endl? try putting std::endl
1,792,578
1,792,591
Benefits of exporting a class from a dll vs. static library
I have a C++ class I'm writing now that will be used all over a project I'm working on. I have the option to put it in a static library, or export the class from a dll. What are the benefits/penalties for each approach. The only one I can think of is compiled code size which I don't really care about. Thanks!
Advantages of a DLL: You can have multiple different exe's that access this functionality, so you will have a smaller project size overall. You can dynamically update your component without replacing the whole exe. If you do this though be careful that the interface remains the same. Sometimes like in the case of LGPL you are forced into using a DLL. You could have some components as C#, Python or other languages that tie into your DLL. You can build programs that consume your DLL that work with different versions of the DLL. For example you could check if a function exists in a certain operating system DLL and only call it if it exists, and otherwise do some other processing. Advantages of Static library: You cannot have dll verisoning problems that way Less to distribute, you aren't forced into a full installer if you only have a small application. You don't have to worry about anyone else tying into your code that would have been accessible if it was a DLL. Easier to develop a static library as you don't need to worry about exports and imports. Memory management is easier.
1,792,581
1,792,735
C++ from C#: C++ function (in a DLL) returning false, but C# thinks it's true!
I'm writing a little C# app that calls a few functions in a C++ API. I have the C++ code building into a DLL, and the C# code calls the API using DllImport. (I am using a .DEF file for the C++ DLL so I don't need extern "C".) So far the API has one function, which currently does absolutely nothing: bool Foo() { return false; } In C#, I have the following: public class FooAPI { [DllImport("Foo.dll")] public static extern bool Foo(); } ... bool b = FooAPI.Foo(); if (!b) { // Throw an exception } My problem is that, for some reason, b is always evaluating to TRUE. I have a breakpoint on if (!b) and the debugger reports it as 'true', irrelevant of whatever the C++ function is returning. Is the C# bool the same as the C++ bool? Though even if this wasn't the case, I still don't get how it would find the return value to be 'true' :) Can anyone help me with this bizarre discrepancy? Thanks in advance!
Try [return: MarshalAs (UnmanagedType.I1)]. By default, C# interop marshals C# bool as the Win32 BOOL, which is the same as int, while C++ bool is one byte AFAIR. Thus, C#'s default marshaling expects the return value to be a BOOL in the eax register, and picks up some non-zero garbage because C++ bool is returned in al.
1,792,678
1,979,344
Wrapping a Lua object for use in C++ with SWIG
Currently I know how to have C++ objects instantiated and passed around in Lua using SWIG bindings, what I need is the reverse. I am using Lua & C++ & SWIG. I have interfaces in C++ and objects in lua, that implement methods which do the same job and have the same structure. I would like to be able to instantiate these objects in lua yet pass them around in C++ using pointers to that interface which they resemble. As such I can imagine creating a c++ implementation of the interface which would act as a handler for said lua object, yet I don't know how to do this. The class would act as the lua objects representative or proxy in the C++ world. To clarify I shall start with the following example code used in an answer to a similar question I asked: C++ code: // Represents a generic bank account class Account { virtual void deposit(double amount) = 0; }; Lua code: SavingsAccount = { balance = 0 } SavingsAccount.deposit = function(amount) SavingsAccount.balance = SavingsAccount.balance + amount end -- Usage a = SavingsAccount a.balance = 100 a.deposit(1000) Now say that I have a class in C++ called Bank: class Bank { void AddAccount(Account* a); }; What I would like here is a mechanism for doing the following in lua: SavingsAccount = { balance = 0 } SavingsAccount.deposit = function(amount) SavingsAccount.balance = SavingsAccount.balance + amount end -- Usage a = SavingsAccount bank:AddAccount(a) If I need to take an extra step such as instantiating a C++ class to act as a proxy and pass it the lua table with all my lua functions etc, I can imagine it looking like this: C++ code: // Represents a generic bank account class ProxyAccount : public Account { virtual void deposit(double amount); }; Lua code: SavingsAccount = { balance = 0 } SavingsAccount.deposit = function(amount) SavingsAccount.balance = SavingsAccount.balance + amount end -- Usage a = SavingsAccount a.balance = 100 a.deposit(1000) proxy = program.ProxyAccount() proxy.settable(a) bank:AddAccount(p) The problem here being I have no idea how I would implement the ProxyAccount class, or even what the function signature of settable would look like...
What I seem to gather from your examples and the discussions is that you are expecting Lua to be the primary language, and C++ to be the client. The problem is, that the Lua C interface is not designed to work like that, Lua is meant to be the client, and all the hard work is meant to be written in C so that Lua can call it effortlessly. Now, the important question is: why don't you want to have a C representation of the object, and prefer to have it in Lua? Since C++ is a much lower level language, and object definitions must be static, and Lua dynamically defines its "objects" it is much easier to have Lua adapt to C++ objects. Another issue I see is that you seem to be designing your Lua code in a very Object Oriented manner. Remember that even though Lua can fake Object Oriented concepts, it is not built as an Object Oriented language, and should not be used primarily as one. If you want a fully OO scripting language, use python instead. Now if you Really want to do it the other way, and considered that the other alternatives do not work for you, then what I would recommend, is that you keep the Lua object as a coroutine, this will allow you to: Keep a representation of the object in C++ (the lua_State *) Have multiple individual instances of the same "object type" Lua takes care of the cleanup However, the downsides are: All functions that act on an "object" need to do so through the lua API There is no easy/fast way to recognize different lua types (you could use a metatable) Implementation is quite cumbersome, and hard to decypher. EDIT: Here is how you could expose the interface to an object in a script, Each object instance would be running a new lua_State, and run its script individually, thus allowing for your "Object member data" to just be globals inside the script instance. Implementing the API for the object's methods would go like this: int move(lua_State * L) { int idx = lua_getglobal(L, "this"); assert(!lua_isnull(-1)); AIObject * obj = static_cast<AIObject *>(lua_touserdata(L, -1)); lua_pop(1); //Pop the other parameters obj->move(/*params*/); }
1,793,037
1,798,973
How do I add a header with data to a QTableWidget in Qt?
I'm still learning Qt and I am indebted to the SO community for providing me with great, very timely answers to my Qt questions. Thank you. I'm quite confused on the idea of adding a header to a QTableWidget. What I'd like to do is have a table that contains information about team members. Each row for a member should contain his first and last name, each in its own cell, an email address in one cell, and office in the other cell. I'd to have a header above these columns to name them as appropriate. I'm trying to start off easy and get just the header to display "Last" (as in last name). Here is my code. int column = m_ui->teamTableWidget->columnCount(); m_ui->teamTableWidget->setColumnCount(column+1); QString* qq = new QString("Last"); m_ui->teamTableWidget->horizontalHeader()->model()->setHeaderData(0, Qt::Horizontal, QVariant(QVariant::String, &qq)); My table gets rendered corretly, but the header doesn't contain what I would expect. It contains 1 cell that contains the text "1". I am obviously doing something very silly here that is wrong, but i am lost. I keep pouring over the documentation, finding nothing. Thanks for any and all help.
At the request of the person who steered me toward the right place, I am posting the way I accomplished this as an answer and I am accepting it. m_ui->teamTableWidget->setColumnCount(m_ui->teamTableWidget->columnCount()+1); QTableWidgetItem* qtwi = new QTableWidgetItem(QString("Last"),QTableWidgetItem::Type); m_ui->teamTableWidget->setHorizontalHeaderItem(0,qtwi);
1,793,082
1,793,127
How to dynamically create a union instance in c++?
I need to have several instances of a union as class variables, so how can I create a union instance in the heap? thank you
The same as creating any other object: union MyUnion { unsigned char charValue[5]; unsigned int intValue; }; MyUnion *myUnion = new MyUnion; Your union is now on the heap. Note that a union is the size of it's largest data member.
1,793,123
1,796,766
Map functions of a class while declaring the functions
My previous question about this subject was answered and I got some tests working nice. Map functions of a class My question is now, if there is a way to while declaring the function, be able to register it in a map, like I realized in this question about namespaces and classes: Somehow register my classes in a list the namespaces and classes was fine to register in a map using the "static" keyword, with that, those static instances would be constructed before the main() be called. Can I do that somehow with class functions? because when I use static keyword inside a class declaration, I can't initialize the member as I can outside the class declaration(as with namespaces and classes in the second url above) I guess I could hardcode all members inside the constructor and register them in a map, but I would like to know if there is a way to do that while I declare the members, to make it easier in the future Thank you, Joe
What is your problem here ? The problem is that, unfortunately, in C++ functions are not considered first class members. Oh sure there are those pointers to functions that work pretty well, but there is no generic function type or anything like that. There are however ways to work around this, the simplest I think being the Command pattern. In the Command pattern a function (operation) is abstracted away in an object. The arguments are stored in the object for later reuse (for example undo or redo command) and a unified interface exists to perform the operation itself. Less talk, more code: class Command { public: virtual ~Command() {} virtual Command* clone() const = 0; virtual void execute() = 0; }; Simple ? class Foo {}; class FooCommand: public Command { public: void parameters(Foo& self, int a, std::string const& b); virtual FooCommand* clone() const; virtual void execute(); private: Foo* m_self; int m_a; std::string const* m_b; }; Now, the sweet thing is that I can simply store my command in a map. // registration typedef boost::ptr_map<std::string, Command> commands_type; commands_type commands; commands.insert("foo", FooCommand()); // get the command Foo foo; FooCommand* cFoo = dynamic_cast<FooCommand*>(commands["foo"].clone()); if (cFoo != 0) { cFoo->parameters(foo, 2, "bar"); cFoo->execute(); } This proposal would still require some work. passing the parameters is quite annoying since it requires a down cast. I did not concern myself with exception safety, but returning an auto_ptr or a shared_ptr would be better for the clone method... the distinction between a const and non-const Foo argument is not that easy to introduce. However it is safer than using a void* to store the pointers to function in you map since you have the advantage of RTTI to check whether or not the type is correct. On the other hand, printing the collection of Commands linked to a particular object is incredibly easy now (if you have one map per object), you can also find ways to emulate the effect of virtual methods etc... But I hope you realize that you are in fact trying to implement reflection, and it's not gonna be easy... good luck!
1,793,257
1,793,293
How can I solve this median programming problem in C++
Formulate the steps of identifying the median from five unique numbers and visualize them in flow chart. Develop an application that shows the median after getting five unique numbers from users. Extend the feature for allowing six unique numbers input and computing the median. Example: Input: 5 4 2 1 10 Output: Median = 4 I found this question in a Problem Solving with C++ by Walter Savitch but I couldn't solve it. Can anyone explain it to me?
Trying to give homework-friendly advice: 1) Make sure you know how to get a Median. Can you, in your head or on paper, figure it out? Now, how do you write a program to do this for you? Make a flowchart. 2) Write the program to do it. A user gives your program 5 numbers, your program gives the median as an answer. 3) Make the program better. An even amount of numbers changes the method to get a median. Change your program so that it will allow 6 numbers. 3b) Make your program accept any amount of numbers. (I added this, not in your post or in your book but should be super-easy to do if you've already done 2 and 3).
1,793,413
1,793,431
Distribute C++ application as .exe or .msi?
I am looking for a program that can take the program I made in Visual C++ 2008 and distribute it in a mature installer for Windows. I want an application that is FREE (or trial). The setup and deployment folder is not there when a select File-->Add-->New Project
You can try NSIS (Nullsoft Scriptable Install System), which is free, but can be confusing because it's lots of scripts. That said, it can do anything you might want to do. Install Creator from ClickTeam is very simple to use and is my preferred application but it does cost money.
1,793,439
1,793,464
Heap Implementations
In a heap implementation of the ADT priority queue, the item with the highest priority value is always in the front or root of the array? Or is it, where the ADT priority queue that has the highest priority value is in the n-1 slot of the array?
The way Priority Queues are implemented, the highest priority value is always at the first (zeroth) position of the array. They are typically implemented as a heap: index 0 1 2 3 4 5 6 7 8 9 parent / 0 0 1 1 2 2 3 3 4 This is because the parent is easily found by (index - 1) / 2 (when using integer division)
1,793,577
1,793,615
Overloading Default Construction with Initializer List
I need to know how to get something to work. I've got a class with a constructor and some constants initialized in the initializer list. What I want is to be able to create a different constructor that takes some extra params but still use the initializer list. Like so: class TestClass { const int cVal; int newX; TestClass(int x) : cVal(10) { newX = x + 1; } TestClass(int i, int j) : TestClass(i) { newX += j; } } Totally terrible example, but it gets the point across. Question is, how do I get this to work?
There's no way for one constructor to delegate to another constructor of the same class. You can refactor common code into a static member function, but the latter cannot initialize fields, so you'll have to repeat field initializers in every constructor you have. If a particular field initializer has a complicated expression computing the value, you can refactor that into a static member function so it can be reused in all constructors. This is a known inconvenience, and a way to delegate to another constructor will be provided in C++0x.
1,793,590
1,796,116
C++ dynamic allocated array
I'm doing some assignment and got stuck at one point here. I am trying to write an list_add() function. The first functionality of it is to add values to the array. The second functionality for it is to increase the size of the array. So it works much like a vector. I dunno if I get it right though. What I tried is to create a new dynamic allocated array which is larger than the old one, and then copy over all the values to the new array. Is it the right approach? Here's the main body int main() { const int N = 7; //declaring dynamic array allocation int* list = new int[N]; int used = 0, a_val; for(int i=0;i<11;i++) { list_add(list, used, N, i); } cout << endl << "Storlek: " << N << endl << endl; cout << "Printar listan " << endl; for(int i=0;i<used;i++) { cout << list[i] << ". "; } } Here's the function bool list_add(int *list, int& space_used, int max_size, int value) { if(max_size-space_used > 0) { *(list+(max_size-space_used-1)) = value; space_used++; return true; } else { cout << "Increasing size of array!" << endl; int new_max_size = space_used+1; delete [] list; int *list_new = new int[new_max_size]; for(int i=0; i<new_max_size; i++) { list_new[i] = i; cout << list_new[i] << ". "; } cout << endl; space_used++; list = list_new; return false; } }
There four problems with the implementation of your code: It doesn't copy the elements of the list. It doesn't assign the value of new_list to the list variable in main It inserts values from the back to the front, instead of after the last value max_size doesn't get updated. It's easy to miss this, because you only increase the size of the array by one each time. That way it would need to allocate each time a value is added. If you increase the new size by more then one it will still reallocate every time. The first problem can be fixed by changing the for loop in list_add so it makes a copy: for (int i = 0; i < space_used; i++) { // this also changed. list_new[i] = list[i]; cout ... } // insert the new value (in the front?) list_new[max_size-space_used-1] = value; delete [] list; // Delete the list afterwards instead of earlier. The second problem can by fixed by returning a pointer to the list. Change the main function to this: for (int i = 0; i < 11; i++) { list = list_add(list, used, N, i); } The third problem can be fixed by changing this line list_new[max_size-space_used-1] = value; to list_new[space_used++] = value; You should also remove the space_used++ after this. To see the fourth problem you should change this line int new_max_size = space_used+1; to int new_max_size = space_used+3; It will still reallocate every time. It should however reallocate only two times. This is the full code: #include <iostream> using std::cout; using std::endl; int* list_add(int *list, int& space_used, int& max_size, int value) { if (max_size - space_used > 0) { list[space_used++] = value; return list; } else { cout << "Increasing size of array!" << endl; int new_max_size = space_used+1; int *list_new = new int[new_max_size]; for (int i = 0; i < space_used; i++) { list_new[i] = list[i]; cout << list_new[i] << ". "; } cout << endl; list_new[space_used++] = value; max_size=new_max_size; delete [] list; return list_new; } } int main() { int N = 7; //declaring dynamic array allocation int* list = new int[N]; int used = 0, a_val; for (int i = 0; i < 11; i++) { list=list_add(list, used, N, i); } cout << endl << "Storlek: " << N << endl << endl; cout << "Printar listan " << endl; for (int i = 0; i < used; i++) { cout << list[i] << ". "; } }
1,793,691
1,793,711
std::time(0) performance
I was wondering what the performance implications are of using std::time(0) to seed random number generators. I assume that it's a system call (if not please correct me), which generally isn't the best option regarding performance. Assuming std::time(0) is used many times throughout a program, will there be severe performance implications if any? P.S. I'm more curious than anything, as currently there aren't any performance issues.
Reseeding the RNG should be a rather rare event, so I don't think you need to be concerned about performance. If you are reseeding frequently enough to cause a performance issue, you might want to rethink your approach -- you may be doing more harm than good.
1,793,800
1,794,089
Can I redefine a C++ macro then define it back?
I am using both the JUCE Library and a number of Boost headers in my code. Juce defines "T" as a macro (groan), and Boost often uses "T" in it's template definitions. The result is that if you somehow include the JUCE headers before the Boost headers the preprocessor expands the JUCE macro in the Boost code, and then the compiler gets hopelessly lost. Keeping my includes in the right order isn't hard most of the time, but it can get tricky when you have a JUCE class that includes some other classes and somewhere up the chain one file includes Boost, and if any of the files before it needed a JUCE include you're in trouble. My initial hope at fixing this was to #undef T before any includes for Boost. But the problem is, if I don't re-define it, then other code gets confused that "T" is not declared. I then thought that maybe I could do some circular #define trickery like so: // some includes up here #define ___T___ T #undef T // include boost headers here #define T ___T___ #undef ___T___ Ugly, but I thought it may work. Sadly no. I get errors in places using "T" as a macro that '___T___' was not declared in this scope. Is there a way to make these two libraries work reliably together?
As greyfade pointed out, your ___T___ trick doesn't work because the preprocessor is a pretty simple creature. An alternative approach is to use pragma directives: // juice includes here #pragma push_macro("T") #undef T // include boost headers here #pragma pop_macro("T") That should work in MSVC++ and GCC has added support for pop_macro and push_macro for compatibility with it. Technically it is implementation-dependent though, but I don't think there's a standard way of temporarily suppressing the definition.
1,793,807
1,793,825
Declaring a variable in an if-else block in C++
I'm trying to declare a variable in an if-else block as follows: int main(int argc, char *argv[]) { if (argv[3] == string("simple")) { Player & player = *get_Simple(); } else if (argv[3] == string("counting")) { Player & player = *get_Counting(); } else if (argv[3] == string("competitor")) { Player & player = *get_Competitor(); } // More code } But, I'm getting the following errors when I try to compile: driver.cpp:38: error: unused variable ‘player’ driver.cpp:40: error: unused variable ‘player’ driver.cpp:42: error: unused variable ‘player’ driver.cpp:45: error: ‘player’ was not declared in this scope Any ideas?
Your problem is that player falls out of scope in each if / else if block. You need to declare your variable above all of the if statements. But you can't use a reference for that because you must initialize a reference right away. Instead you probably want something like this: int main(int argc, char *argv[]) { Player * pPlayer = NULL; if (argv[3] == string("simple")) { pPlayer = get_Simple(); } else if (argv[3] == string("counting")) { pPlayer = get_Counting(); } else if (argv[3] == string("competitor")) { pPlayer = get_Competitor(); } //Then if you really want to... Player &player = *pPlayer; }
1,793,884
1,794,063
QComboBox with single value: Select this value
I have a QComboBox which changes its selection possibilities depending on certain conditions. Because of special combinations, it might have only one selection left over, which has to be "confirmed" by the user, preferably by looking at all possible selections, seeing that there is only one, and then selecting this. My problem: If a user selects the only option there is, the value is never set, i.e. no signal is sent. Is there a way to circumvent this?
Use SIGNAL(highlighted(...)) instead of SIGNAL(activated(...)). Or do a setCurrentIndex(-1) before, this should work with activated().
1,794,069
1,794,082
Why do I get an EXC_BAD_ACCESS here and how can I make it work?
I'm trying to make my code be able to separate a file into a customer database (it's delimited by many spaces and not tabs). I try to use strtok, but I get an EXC_BAD_ACCESS error. Here is my main.cpp code: #include <iostream> #include <fstream> #include <string> #include <sstream> #include "Cust.h" using namespace std; int main (int argc, char * const argv[]) { Cust customers[500]; int idx = 0; string tmpString = ""; string tmpAcctFN = ""; string tmpAcctLN = ""; ifstream input("P3_custData.txt"); while (!input.eof()){ getline(input,tmpString); tmpString.insert(0,""); customers[idx].setAcctNum(atoi(strtok((char *)tmpString.c_str()," "))); customers[idx].setAcctFN(strtok(NULL," ")); customers[idx].setAcctLN(strtok(NULL," ")); //customers[idx].setCurrBalance(atof(strtok((char *) tmpString.c_str()," "))); } cout << "return 0;"; return 0; } I still get an EXC_BAD_ACCESS after making changes based on the comments: #include <iostream> #include <fstream> #include <string> #include <sstream> #include "Cust.h" using namespace std; int main (int argc, char * const argv[]) { Cust customers[500]; int idx = 0; string tmpString = ""; string tmpAcctFN = ""; string tmpAcctLN = ""; char * s; ifstream input("P3_custData.txt"); while (!input.eof()){ getline(input,tmpString); s = strdup (tmpString.c_str()); customers[idx].setAcctNum(atoi(strtok(s," "))); customers[idx].setAcctFN(strtok(NULL," ")); customers[idx].setAcctLN(strtok(NULL," ")); //customers[idx].setCurrBalance(atof(strtok((char *) tmpString.c_str()," "))); } cout << "return 0;"; return 0; }
It is illegal to attempt to modify the string returned by std::string::c_str() method. strtok will make such an attempt (the fact that you had to cast away the constness of the returned string is a dead giveaway). In other words, you can't use strtok on the result of std::string::c_str(). Either get rid of strtok (better), or create a standalone modifiable copy of the string and use strtok on it (worse).
1,794,223
1,794,580
Ideas for computer science project with CORBA or ICE
We have to perform a semester project with distributed computing using CORBA or ICE. It is a single-person project and we have a couple of months of time. For the programming language I'd like to focus on c# for it may be any other like C++. I don't want to write the one millionth prime generator, maybe there is something much more interesting which I didn't think of yet..
If I were you, ....what I would do is go to your prof and ask to work outside the lines. Ask to be released from the CORBA or ICE requirement. Ask if you can use something that is NOT Corba. Ask if you can use REST, or XML Web services, or even protobufs. CORBA is not irrelevant, as far as the principles go, but it is nearly irrelevant in commercial appeal. Do something that will teach you some more current skills. To me, it would be like studying vacuum tubes. Interesting academically and scientifically, but... Rather than a prime number generator, why not get a little more interesting? a distributed hash table, something like the new BitTorrent design. a work distribution system for a compute farm. How would you build a distributed map/reduce across that farm? you could do encryption, compression, video ripping. Build a general purpose distributed work management system that would be appropriate for any of those jobs, with a modular architecture. How would you detect failures (host offline or non-responsive)? How would you deal with rescusitated hosts? a SETI-@Home type of network. or protein folding. or climate trend analysis (using Public Domain databases - http://en.wikipedia.org/wiki/Public_Domain_Resource ) Something where you're doing something more practical than computing prime numbers. OR - actually do the prime number problem, but apply it to cryptography, breaking keys. a network of agents, where you actually distribute code to the nodes to execute. Something like JavaSpaces. a poker bot. just some ideas.
1,794,233
1,794,389
Is there any good tree manipulation (template) libraries for C++ out there?
Is there any good tree manipulation (template) libraries for C++ out there that can do basic things like binary tree. Though it is not difficult to write a binary tree all from scratch, but I'm really surprised that it is not so easy to find one ready-for-use.
What do you need the tree for? There may already be something in the STL or Boost that satisfies your need. For example: the STL std::map<key,value> is usually implemented as a balanced binary tree. There is also tree.hh which implements an STL-like n-way tree.
1,794,271
1,794,462
Could not deduce template argument for T[]
Now I'm getting another error. error C2065: 'temp' : undeclared identifier I know that for temp I need to declare the type of the array like int temp[], but what if I don't know what it is? It could be int or string or double. How can I create a temp array without specifying its type? I added my Mergesort function. Here is my code: template<class T> void Mergesort(T& a, int first, int last); template<class T> void Merge(T& a, int first, int last); int main() { int num; cout << "How many words? "; cin >> num; Array<string> b(num); cout << "Enter the " << num << " words below:\n"; for (int i=0; i<num ; i++) cin >> b[i]; cout << "\nThank you!!\n"; // Copy the original array and sort it using Quicksort Array<string> bq(b); Quicksort(bq, 0, num-1); cout << "\nElements sorted using quicksort:\n"; for (int i=0; i<num ; i++) cout << bq[i]<< " "; cout << "\n"; Array<string> bm(b); Mergesort(bm, 0, num-1); cout << "\nElements sorted using mergesort:\n"; for (int i=0; i<num ; i++) cout << bm[i]<< " "; cout << "\n"; } template<class T> void Mergesort(T& a, int first, int last) { if (first < last) { int mid = (first + last) / 2; Mergesort(a, first, mid); Mergesort(a, mid+1, last); Merge(a, first, last); } } template<class T> void Merge(T& a, int first, int last) { int mid = (first + last) / 2; int one = 0, two = first, three = mid + 1; while (two <= mid && three <= last) // Neither sublist is done if (a[two] < a[three]) // Value in first half is smaller temp[one++] = a[two++]; else // Value in second half is smaller temp[one++] = a[three++]; while (two <= mid) // Finish copying first half temp[one++] = a[two++]; while (three <= last) // Finish copying second half temp[one++] = a[three++]; for (one = 0, two = first; two <= last; a[two++] = temp[one++]); } ARRAY.h using namespace std; template<class T> class Array { public: Array(int s); Array(int l, int h); Array(const Array& other); ~Array(); T& operator[](int index); const T& operator[](int index) const; int get_size() const {return arraySize;} private: int low; int high; int arraySize; //size of array int offset; //to adjust back to an index of zero T *array_; void Copy(const Array&); };
T a[] means you expect an array of T as the parameter type - but thats a C array, not a class type. Your class template Array is just that - a class template that only happens to provide convenience access to its contents via operator[](). To fix the first error change Quicksort()s signature to: template<class T> void Quicksort(T& a, int first, int last) Then there is the problem that you use T for a local variable pivot. To do that generically with containers, it is more or less standard to provide a typedef named value_type for the contained types (the values) of the container: template<class T> class Array { public: typedef T value_type; // ... }; With that convention you can declare pivot as follows: T::value_type pivot;
1,794,418
1,798,312
Boost Property Tree and Xml parsing Problems
I'm using boost::property_tree. The documentation is very vague and overall unhelpful for the most part. Looking at the source/examples didn't help that much, either. What I'm wondering is the following: <VGHL> <StringTable> <Language>EN</Language> <DataPath>..\\Data\\Resources\\Strings\\stringtable.bst</DataPath> </StringTable> </VGHL> How can I iterate over all the elements at the current level? If I do this: read_xml(fin, bifPropTree); VGHL::String tablePath; BOOST_FOREACH(boost::property_tree::wiptree::value_type &v, bifPropTree.get_child(L"VGHL.StringTable")) { m_StringTable->ParseEntry(v.second, tablePath); } In ParseEntry I try this: VGHL::String langName = stringTree.get<VGHL::String>(L"StringTable.Language"); Results in an exception (not doesn't exist). I've also tried this: VGHL::String langName = stringTree.get<VGHL::String>(L"Language"); Same problem. From my understanding when I call ParseEntry I am passing a reference to the tree at that node. Is there any way to deal with this, when I have multiple entries of StringTable using property tree?
ParseEntry receives a reference to each of the children nodes of the current level. So, you cannot ask the values using the node name, because you already have a child node. The node name is stored in v.first. You can iterate over all the elements at a given level using get_child to select the level and then BOOST_FOREACH to iterate. Each iterator will be a pair representing the name of the node and the node data: using boost::property_tree::wiptree; wiptree &iterationLevel = bifPropTree.get_child(L"VGHL.StringTable"); BOOST_FOREACH(wiptree::value_type &v, iterationLevel) { wstring name = v.first; wstring value = v.second.get<wstring>(L""); wcout << L"Name: " << name << L", Value: " << value.c_str() << endl; } This code would print: Name: Language, Value: EN Name: DataPath, Value: ..\\Data\\Resources\\Strings\\stringtable.bst If you do not want to iterate, you can select the node level and then look for the nodes using their name: wiptree &iterationLevel = bifPropTree.get_child(L"VGHL.StringTable"); wstring valueLang = iterationLevel.get<wstring>(L"Language"); wstring valuePath = iterationLevel.get<wstring>(L"DataPath"); wcout << valueLang << endl << valuePath << endl; This code would print: EN ..\\Data\\Resources\\Strings\\stringtable.bst
1,794,640
1,794,926
Function Template Specialization on Function Pointers
I have a sanitization function that I want to run on (traditional) pointer types only. My problem is with function templates I can get as far as limiting the function to only pointers, however because of casting rule differences between function pointers and regular pointers, I run into problems. The Sanitize() function needs to run against a whole slew of types, some of which are pointers and need to be sanitized, others of which are function pointers of varying arity and parameter types and should not be sanitized, and some of which are non-pointer data types which also should not be sanitized. Anything obvious I'm missing? template<typename T> T* Sanitize(T* value) { return (T*)SanitizePointer(value); //SanitizePointer returns void*, so cast is necessary } template<typename T> T Sanitize(T value) { return value; //Non-pointers can be passed without sanitization } int main() { int a; int* b; int (*c)(); Sanitize(a); Sanitize(b); Sanitize(c); //<- ERROR return 0; }
While this problem could be solved manually, its easiest to utilize Boosts type traits and SFINAE helper to selectively disable the overload for pointers if T* is a function pointer: template<typename T> typename boost::disable_if<boost::is_function<T>, T*>::type Sanitize(T* value) { // ... }
1,794,689
1,794,768
Code smell in this switch statement?
I'm wondering where a switch statement of this style should be changed to an if else statement. switch (foo) // foo is an enumerated type { case barOne: if (blahOne) { DoFunction(//parameters specific to barOne); break; } case barTwo: if (blahTwo) { DoFunction(//parameters specific to barTwo); break; } //etc. default: // Whatever happens if none of the case's conditionals are met } Basically fall through is happening unless a condition is met for one of the cases. The cases are very similar, differing only in what needs to be checked for and what needs to be passed, which is why I used a switch statement. Would it be better to use if else if? Otherwise, is it clear enough to stay, but unclear enough to warrant a comment about the fallthrough? Polymorphism is also always an option, but it seems like overkill to me.
It seems like this might do strange things in some cases. What if foo == bar1, and blahOne is false, but blahTwo is true? Then you'll fall through and call the function under the foo == bar2 case, even though foo doesn't equal bar2. That might be unexpected in practice, but if it ever did occur it might be tough to debug. I'd vote for an if else in this case, because the flow is simpler. if (foo == barOne && blahOne) { DoFunction(/*parameters specific to barOne*/); } else if (foo == barTwo && blahTwo) { DoFunction(/*parameters specific to barTwo*/); } else { // Handle the fallthrough case. } Of course, if the intention is that blahTwo can be evaluated even though foo != barTwo, then the switch might be the best way to do it, but I'd definitely be in favor of some explanatory comments in that case.
1,794,818
1,794,830
Measuring absolute time taken by a process
I am measuring time taken by my process using QueryPerformanceCounter and QueryPerformanceFrequency. It works fine. As my system is a single processor based system. So many process sharing it.Is it possible to measure CPU time allotted to my process. SO that i can measure absolute time taken. Platform : Windows Language : C++
GetProcessTimes is probably the call you're looking for.
1,794,919
2,119,338
Finding the index of an entry in a linked list in better than O(n) time
I have a scenario where I'm pushing change-lists to another system. Each list contains zero or more inserted, updated or deleted notifications. Inserting is easy; the notification contains the target index and a pointer to the item. Updating is easy; I pass a pointer to the item. Deleting seems straight-forward; I need to pass the index of the item to delete, but how do I know the index? Indexes start at zero and must be contiguous, but I make them up at insertion time. So I need to keep track of the index I make up for each item. I can do this with, for example, a map: std::map<item*, int>, but then when I remove an item, I have to go re-number everything past it, which is O(N). These lists of items are going to be large to the point where O(N) iteration is not acceptable. I'm sure this problem has been solved, I just don't know what the solution would be called. Searching for anything related to "linked list" creates a ton of noise. One possible solution is a skip-list, where each node in the sublists knows how many nodes in the main list it skips, and since searching a skip list is O(log N) we can keep track as we go and find the index in O(log N) and also delete items in O(log N). However implementing a skip-list seems like overkill here... is there a simpler solution? EDIT: Thanks all for your suggestions, but I think I've convinced myself the skip list is the right way to solve this problem here.
Skip List is the correct solution.
1,795,013
1,795,041
C++: how to use std::less<int> with boost::bind and boost::lambda?
I am trying to lean boost::bind, boost::lambda libraries and how they can be used with STL algorithms. Suppose I have vector of int-string pairs which is sorted by int key. Then a place to insert a new pair while keeping the vector sorted can be found as follows: std::vector<std::pair<int, string> > entries; ... int k = ...; // Let's ignore std::lower_bound return value for now std::lower_bound (entries.begin(), entries.end(), k, boost::bind (&std::pair<int, string>::first, _1) < k) Now I would like to replace operator< with a function object (of type std::less<int> in this example): std::less<int> comparator; How do I change the code above so it works? I cannot just do std::lower_bound (entries.begin(), entries.end(), k, comparator (boost::bind (&std::pair<int, string>::first, _1), k)) because std::less<int>::operator() does not accept whatever is the return type of boost::bind. What am I missing here? TIA
All you're missing is another bind (and the template parameters on pair): std::lower_bound(entries.begin(), entries.end(), k, boost::bind(comparator, boost::bind(&std::pair<int, string>::first, _1), k)) You don't have to do that on the less-than operator in your original code because Boost.Bind provides overloads for that operator that know how to handle the return type of boost::bind.
1,795,020
1,811,399
C++ and C# COM Event Performance. Help
Good day. CppApp and CsApp Event Handle Design Changed. For Industry application. Old design. CsApp pull event from CppApp. There are a lot of events from CppApp. So we created two threads in CsApp to handle the events from CppApp. It worked very well. New design. CsApp and CppApp com event (fire event method) design instead of the push/pull event method. Only one pointer in Cpp IDL file created, but it could still handle two fire events function, we didn't change the CppApp event related part code. That means One Com Event Channel between CppApp and CsApp now. Test Result. We tested and it on simulation mode and it worked very well. But there is not enough real machine online testing till now. Specially there where be a lot of event at industry online production envrionment. We worry about if there is some Com Event Sending from CppApp to CsApp delay. Is there any resource which i could research about Com Event performance for industry application? Thanks a lot in advance here. BR! Nano
It isn't clear to me what the difference is between "we tested and it on simulation mode and it worked very well" and "real machine online testing at industry online production envrionment": What are the differences between the simulation machine and the production machine? Can you simulate these differences? When you say that you "tested it on simulation mode", did you do performance/load testing (generating, in your simulation, as many events per second as you expect on the real machine)? Do you allow any extra margin for safety (e.g., I might feel comfortable if my testing shows that my software needs only 10% of the machine's CPU capacity ... because then even if if it needs 10 times more than that in real life, that's still enough)? The end-user/customer will eventually do acceptance testing on the real machine. Can you work with them, to get you access to the real machine? We worry about if there is some Com Event Sending from CppApp to CsApp delay Well, COM is faster when it's used in-process instead of inter-process or out-of-process: when the COM object is a DLL loaded into the same process as whatever is using it. Is there any resource which i could research about Com Event performance for industry application? I don't know; for what it's worth, the article Events vs. Callbacks says, Performance Issues When performance is at stake, it will usually be worthwhile to do the extra work required to create custom callback interfaces. By employing early binding in the callback interface connection code, significant improvements can be made in high-volume or in-process components. By design, event interfaces are not vtable bound and are, therefore, slower in most scenarios than comparable early-bound callback interfaces. Of course, in any performance issue, the only way to gauge your own needs is to experiment, benchmark, and test. Try out the various permutations yourself and do the math. If you really care about getting the absolute last spurt of speed, then doing the tests is the only way to prove what works, no matter what promises are made. Other articles in that section of MSDN are also relevent to performance, for example Understanding and Using COM Threading Models
1,795,021
1,795,126
Writing a C++ DLL, then wrapping it in C#
I am a bit confused about wrapping a c++ dll in c#. What kind of dll should i create? A normal dll or an mfc dll? Should i prefix every proto with "extern..." ? Should i write the functions in a def file? My last effort was in vain, c# would crash with an error like "bad image format", which means that the dll format is not correct? Any help would be much appreciated. Thanks in advance :-)
Are you using a 64-bit PC? "Bad image format" will occur on an x64 system if you try to mix x64 code and x86 code. This will happen if you write C# code (targeted to "Any CPU", so it'll jit-compile to x64 code) that calls an unmanaged DLL (that will probably be x86 by default). Two solutions to this are: (Proper solution) Make sure the dll is compiled to target x64 so the whole program can run as a native 64-bit app, or (Backwards compatibility solution) Force your whole application to run as an x86 app. In the C# project properties, change the Build "Any CPU" setting to "x86". Otherwise, you should be able to create a normal COM dll (with or without MFC shouldn't matter) and then just wrap it in an RCW (Runtime callable wrapper).
1,795,658
1,858,689
Looping over the non-zero elements of a uBlas sparse matrix
I have the following sparse matrix that contains O(N) elements boost::numeric::ublas::compressed_matrix<int> adjacency (N, N); I could write a brute force double loop to go over all the entries in O(N^2) time like below, but this is going to be too slow. for(int i=0; i<N; ++i) for(int j=0; j<N; ++j) std::cout << adjacency(i,j) std::endl; How can I loop over only the non-zero entries in O(N) time? For each non-zero element I would like to have access to its value, and the indexes i,j.
You can find the answer in this FAQ: How to iterate over all non zero elements? In your case it would be: typedef boost::numeric::ublas::compressed_matrix<int>::iterator1 it1_t; typedef boost::numeric::ublas::compressed_matrix<int>::iterator2 it2_t; for (it1_t it1 = adjacency.begin1(); it1 != adjacency.end1(); it1++) { for (it2_t it2 = it1.begin(); it2 != it1.end(); it2++) { std::cout << "(" << it2.index1() << "," << it2.index2() << ") = "; std::cout << *it2 << std::endl; } }
1,795,784
1,795,858
Copy to Program Files under Windows Vista/7
I have written a wizard in C++ which installs some files to the program files folder under windows. As I understand, I need Admin rights to write to program files under Vista/7. So my question is: Is there a way to turn on Admin rights while the application is running respectively only for one wizard page? Or do I have to start another process with Admin rights for this one wizard page?
Typically you have a shield logo'd button and then shell out to another process whose manifest requests elevation. But really it sounds like you're writing an installer so you should use something designed for that like WiX. See also this similar question and this cited article from one of the answers thereof
1,795,816
1,795,950
Can a C++ Class Constructor Know Its Instance Name?
Is it possible to know the object instance name / variable name from within a class method? For example: #include <iostream> using namespace std; class Foo { public: void Print(); }; void Foo::Print() { // what should be ????????? below ? // cout << "Instance name = " << ?????????; } int main() { Foo a, b; a.Print(); b.Print(); return 0; }
Not with the language itself, but you could code something like: #include <iostream> #include <string> class Foo { public: Foo(const std::string& name) { m_name = name;} void Print() { std::cout << "Instance name = " << m_name << std::endl; } private: std::string m_name; }; int main() { Foo a("a"); Foo b("b"); a.Print(); b.Print(); return 0; }
1,796,030
1,796,849
What kind of message can be transported through ActiveMQ?
We are building a distributed system, maybe a c# app will talk to a c++ app, and maybe some jpeg image will ben send between, is this possible with Activemq?
As far as I know, you can transport any XML message, and also binary messages (blob messages, see http://activemq.apache.org/blob-messages.html). Since ActiveMQ won't try to interpret the binary message, you can safely send JPEGs or other stuff around.
1,796,046
1,796,154
Can a reference type be used as the key type in an STL map
Can I construct an std::map where the key type is a reference type, e.g. Foo & and if not, why not?
According to C++ Standard 23.1.2/7 key_type should be assignable. Reference type is not.
1,796,193
1,798,058
Mysql++ "undefined reference to __imp___ZN7mysqlpp10ConnectionC1Eb"
I am trying to install the mysql++ in Code::Blocks, but When I try to run the example code I get this error: undefined reference to __imp___ZN7mysqlpp10ConnectionC1Eb What I am doing wrong?
You must build MySQL++ with the exact same compiler and compiler options as you're using to build your program. What you're seeing is a name mangling and/or ABI mismatch due to mixing compilers and/or build options. This can be anything from a drastic error like trying to use a Visual C++ DLL with MinGW, to something more subtle like trying to use a MinGW DLL built with g++ 3.4.5 in a program you're building with MinGW g++ 4.4. Unlike C, C++ doesn't try to preserve binary compatibility between greatly different compilers.
1,796,225
1,796,845
Get stack trace from uncaught exception?
I realise this will be platform specific: is there any way to get a stack trace from an uncaught C++ exception, but from the point at which the exception is thrown? I have a Windows Structured Exception Handler to catch access violations, etc. and generate a minidump. But of course that won't get called in the event of termination due to an uncaught C++ exception, and so there is no crash dump. I'm looking for a Windows solution at the moment (no matter how dirty!), but would like to hear about other platforms if possible. Thanks.
We implemented MiniDumps for unhandled exceptions in our last title using the information from this site: http://beefchunk.com/documentation/sys-programming/os-win32/debug/www.debuginfo.com/articles/effminidumps.html And to catch the unhandled exceptions on windows have a look at: SetUnhandledExceptionFilter (http://msdn.microsoft.com/en-us/library/ms680634%28VS.85%29.aspx). As an aisde, we spent a lot of time experimenting with the different levels of minidump until we settled on one. This proved to be of no real use in real world crashes as we had no idea what they would be at the time the minidumps were implemented. It's very application specific, and also crash specific, so my recommendation is to add the minidump handler as early as possible, it will grow with the project and through QA and it will be a life saver at somepoint (and hopefully out in the real world too).
1,796,353
1,796,857
CMake linking problem
I am trying to use CMake to compile a C++ application that uses the C library GStreamer. My main.cpp file looks like this: extern "C" { #include <gst/gst.h> #include <glib.h> } int main(int argc, char* argv[]) { GMainLoop *loop; GstElement *pipeline, *source, *demuxer, *decoder, *conv, *sink; GstBus *bus; /* Initialisation */ gst_init (&argc, &argv); return 0; } This works: g++ -Wall $(pkg-config --cflags --libs gstreamer-0.10) main.cpp -o MPEG4GStreamer How to I make it with CMake? My CMakeLists.txt file looks like this: cmake_minimum_required (VERSION 2.6) project (MPEG4GStreamer) add_executable (MPEG4GStreamer main.cpp) include(${CMAKE_ROOT}/Modules/FindPkgConfig.cmake) # Set CMAKE_C_FLAGS variable with info from pkg-util execute_process(COMMAND pkg-config --cflags gstreamer-0.10 OUTPUT_VARIABLE CMAKE_C_FLAGS) string(REPLACE "\n" "" CMAKE_C_FLAGS ${CMAKE_C_FLAGS}) message("CMAKE_C_FLAGS: ${CMAKE_C_FLAGS}") # Set CMAKE_LINKER_FLAGS variable with info from pkg-util execute_process(COMMAND pkg-config --libs gstreamer-0.10 OUTPUT_VARIABLE CMAKE_LINKER_FLAGS) string(REPLACE "\n" "" CMAKE_LINKER_FLAGS ${CMAKE_LINKER_FLAGS}) message("CMAKE_LINKER_FLAGS: ${CMAKE_LINKER_FLAGS}") set_target_properties(MPEG4GStreamer PROPERTIES COMPILE_FLAGS ${CMAKE_C_FLAGS} LINKER_FLAGS ${CMAKE_LINKER_FLAGS}) Output give a linker error: ~ $ cmake . CMAKE_C_FLAGS: -D_REENTRANT -I/usr/include/libxml2 -I/opt/local/include/gstreamer-0.10 -I/opt/local/include/glib-2.0 -I/opt/local/lib/glib-2.0/include -I/opt/local/include CMAKE_LINKER_FLAGS: -L/opt/local/lib -lgstreamer-0.10 -lgobject-2.0 -lgmodule-2.0 -lgthread-2.0 -lxml2 -lpthread -lz -lm -lglib-2.0 -lintl -liconv -- Configuring done -- Generating done -- Build files have been written to: /Users/francis/ ~ $ make Linking CXX executable MPEG4GStreamer Undefined symbols: "_gst_init", referenced from: _main in main.cpp.o ld: symbol(s) not found collect2: ld returned 1 exit status make[2]: *** [MPEG4GStreamer] Error 1 make[1]: *** [CMakeFiles/MPEG4GStreamer.dir/all] Error 2 make: *** [all] Error 2 ~ $
Doh, just needed to replace CMAKE_LINKER_FLAGS with CMAKE_EXE_LINKER_FLAGS.
1,796,524
1,796,548
Member assignment in a const function
I have a class member myMember that is a myType pointer. I want to assign this member in a function that is declared as const. I'm doing as follows: void func() const { ... const_cast<myType*>(myMember) = new myType(); ... } Doing this works fine in VC++, but GCC gives an error with the message "lvalue required as left operand of assignment". Making the member mutable allow me to simply remove the const_cast and assign the value. However, I'm not entirely sure that that comes with other side-effects. Can I assign my member without having to make the member mutable? How? Are there any side-effects in making members mutable?
The code wont actually work in VC++ - you're not updating the value (or at least it shouldnt), hence the warning from GCC. Correct code is const_cast<myType*&>(myMember) = new myType(); or [from other response, thanks :P]: const_cast<ThisType*>(this)->myMember = new myType(); Making it mutable effectively means you get implicit const_casts in const member functions, which is generally what you should be steering towards when you find yourself doing loads of const_casts on this. There are no 'side-effects to using mutable' other than that. As you can see from the vehement debates circling this question, willy-nilly usage of mutable and lots of const_casts can definitely be symptoms of bad smells in your code. From a conceptual point of view, casting away constness or using mutable can have much larger implications. In some cases, the correct thing to do may be to change the method to non-const, i.e., own up to the fact that it is modifying state. It all depends on how much const-correctness matters in your context - you dont want to end up just sprinking mutable around like pixie dust to make stuff work, but mutable is intended for usage if the member isnt part of the observable state of the object. The most stringent view of const-correctness would hold that not a single bit of the object's state can be modified (e.g., this might be critical if you're instance is in ROM...) - in those cases you dont want any constness to be lost. In other cases, you might have some external state stored somewhere ouside of the object - e.g., a thread-specific cache which also needs to be considered when deciding if it is appropriate.
1,796,587
1,796,617
How to use std::wstring with std::istringstream?
I am trying to write a template function which will extract the value of the given datatype from the given string. I came up with something like this: template<class T> static T getValue(const CString& val_in) { std::wstring value = val_in; std::istringstream iss; iss.str(value); T val = T(); iss>>val; return val; } But this gives the following error for the iss.str(value) statement. error C2664: 'void std::basic_istringstream<_Elem,_Traits,_Alloc>::str(const std::basic_string<_Elem,_Traits,_Ax> &)' : cannot convert parameter 1 from 'std::wstring' to 'const std::basic_string<_Elem,_Traits,_Ax> &' So basically, std::istringstream is accepting only std::string . I thought there may be a std::wistringstream but there doesn't seem to be one available. Any clues how can I do it?
My compiler has wistringstream -- this is all it is: typedef basic_istringstream<wchar_t> wistringstream;
1,796,629
1,797,860
Compile issues based on different platforms
I'm compiling a solution which runs fine on the PC but when trying to compile it for a different platform I get the following error: "Unhandled Exception: System.ArgumentException: An item with the same key has already been added." Anyone know what it could mean?
This is a .NET exception message. Hmm, you definitely tagged it as C++. I'd guess you found a bug in your IDE or whatever tool you use to build your project.
1,796,829
1,796,865
Is there any C++ code beautifuler plug-in for eclipse?
I found a very tempting function in Netbeans, which is to re-factor or 'beautiful-ize' the c++ code according to some parameters, such as tab length, {'s position, etc is there anything similar in Eclipse, which keyword should I google?
Go to your code window Right click Select "Source" then "Format" This should reformat your code according to the options given in the Preferences => "C/C++" => "Code Style
1,797,128
1,797,813
Programmatically differentiating between USB Floppy Drive and USB Flash Drive in Windows
On Windows (XP-7), is there a reliable way of programatically differentiating between USB floppy drives and USB flash drives in C++? At the moment, I'm using WMI to get updates when new Win32_LogicalDisk instances are detected, and then using the DriveType attribute of the LogicalDisk object to figure out a basic type. This works quite well, except that floppy drives and USB flash drives are both of DriveType DRIVE_REMOVABLE, so to differentiate between those (floppy vs. flash), I'm using the IOCTL_STORAGE_GET_HOTPLUG_INFO interface to figure out if the device is hotpluggable, and was working on the principal that that meant it was a flash drive and not a floppy. Again, I think this works quite well (if a little inefficient, using both the WDK API and WMI to get info ) in the case of internal floppy drives, but unfortunately USB Floppy drives are also hotpluggable a lot of the time, so there is no clear way to differentiate between flash and USB floppy drives, that I can see. I know there are properties that may work, like checking if its mapped to the reserved drives A: or B (edit: only relevant if the machine definitely has a floppy drive - see MS-KB: How to change drive letter assignments in Windows XP), or looking at the description, but I'd really like something a bit more reliable. Sorry about the long explanation, but just wanted to be clear! Thanks
Did you try Win32_LogicalDisk.MediaType? It has specific enumerations for floppy disks. Make sure you try it when there's no disk in the drive.
1,797,240
1,797,317
Implementing a File Object (C++)
I've been looking over the Doom 3 SDK code, specifically their File System implementation. The system works (the code I have access to at least) by passing around an 'idFile' object and I've noticed that this class provides read and write methods as well as maintaining a FILE* member. This suggests to me that either the FILE* is 'opened' with read and write access or the file is closed and reopened (with the appropriate access) between calls to Read() and Write(). Does this sound correct or am I over simplifying it? If this isn't the case (which part of me suspects it isn't - due to speed etc.) does anyone have any suggestions as to how they would achieve this elegant interface? Please bare in mind that I am fairly new to both C++ and stdio (which I'm pretty sure iD favours).
You can open a FILE* in read-write mode. If you do that, you should flush and seek to a known location when changing between reading and writing, but you don't have to reopen the file.
1,797,287
1,797,464
virtual function - vtable
Let's say I have class A who inherits from class B and C (multiple inheritance). How many vtable members class A would have ? What's the case in single inheritance ? In addition, suppose: Class A : Public B {} and: B* test = new A(); Where does test gets its vtable from? What's assignment? I assume it gets B's part of A's vtable, but does A's constructor changes its fathers (B) vtable too ?
First, vtable's are implementation specific. In fact, nowhere in the standard is specified that vtable's must exist at all. Anyway, in most usual cases, you would get one vtable pointer per base class with virtual functions. And, as Yuval explained, nobody "fills" the vtable's when an object is constructed; you have one vtable per class with virtual functions, and objects just have pointers to their correct vtable (or vtable's, in case of multiple inheritance). In your single-inheritance example, test would have a pointer to A's vtable, assuming that A has at least one virtual function (inherited from B or newly declared in A).
1,797,351
1,797,760
virtual derived class of a non-virtual base class
I have a virtual class that has been derived from a non virtual class. But when I c-style cast the derived class to base class, the class is corrupted. I am looking at the member variables using the debugger and the member variables are all corrupted when I do that cast. I see there is a 4 byte discrepency when I do that cast(may be the virtual pointer) using debugger. For Ex: class A//non-virtual class { ~A(); int fd; }; class B:public A { virtual ~B(); }; Now say the address of obj of type B is: 0x9354ed0. Now when I cast it (A*)(0x9354ed0) debugger moves the bytes by 4 bytes. So starting address of the casted obj is 0x935ed4 Is it wrong to cast a derived virtual class to base non-virtual class? What is the reason for 4 byte discrepancy? And what is the right way to cast it? Thanks for any input or explanation.
When you cast pointers across the hierarchy, actual numerical pointer values might change. There's nothing wrong with the fact that it changes. There's noting wrong with such a cast. How the numerical pointer values change depend on the physical layout of the class. It is an implementation detail. In your example, the 4 byte change in pointer value might easily be caused by the presence of virtual table pointer in the derived class. The change in pointer value will not corrupt any member variables. The example in your original post does not show any "corrupted member variables" and in general your claim about some member variables getting "corrupted" doesn't make much sense. Please, when you make such claims, illustrate them with an example, so that people can understand what on Earth your are talking about. Update: The fact that base class subobjects might have non-zero offsets inside the derived classes immediately mean that in order to perform a proper cast from derived pointer type to base pointer type the compiler must know the source type and the destination type and the relationship between them. For example, if you do this B* pb = /* whatever */; A* pa = pb; the compiler will know how to properly offset pointer pa from pointer pb. But of you do this A* pa = (void *) pb; the compiler will forget about the relationship between A and B, fail to perform the proper offset and produce the invalid value of pa. The effect would be the same as in A* pa = reinterpret_cast<A*>(pb); If you do it this way, the result will be meaningless. So, just don't do it. Of course, if you manually inspect the numerical value of pb and find out that it is, say, 0x12345678, and then do A* pa = (A*) 0x12345678; you will also get completely meaningless results, because the computer has no way to know that it has to perform the proper offset of the pointer. This will produce an illusion of members of A getting "corrupted", while in fact the only thing that is corrupted is your pointer. And you are the one who corrupted it.
1,797,380
1,797,539
Template specialization with a templatized type
I want to specialize a class template with the following function: template <typename T> class Foo { public: static int bar(); }; The function has no arguments and shall return a result based on the type of Foo. (In this toy example, we return the number of bytes of the type, but in the actual application we want to return some meta-data object.) The specialization works for fully specified types: // specialization 1: works template <> int Foo<int>::bar() { return 4; } // specialization 2: works template <> int Foo<double>::bar() { return 8; } // specialization 3: works typedef pair<int, int> IntPair; template <> int Foo<IntPair>::bar() { return 2 * Foo<int>::bar(); } However, I would like to generalize this to types that depend on (other) template parameters themselves. Adding the following specialization gives a compile-time error (VS2005): // specialization 4: ERROR! template <> template <typename U, typename V> int Foo<std::pair<U, V> >::bar() { return Foo<U>::bar() + Foo<V>::bar(); } I am assuming this is not legal C++, but why? And is there a way to implement this type of pattern elegantly?
Partitial specialization is valid only for classes, not functions. Workaround: template <typename U, typename V> class Foo<std::pair<U, V> > { public: static int bar() { return Foo<U>::bar() + Foo<V>::bar(); } }; If you does not want to specialize class fully, use auxiliary struct template<class T> struct aux { static int bar(); }; template <>int aux <int>::bar() { return 4; } template <>int aux <double>::bar() { return 8; } template <typename U, typename V> struct aux <std::pair<U, V> > { static int bar() { return Foo<U>::bar() + Foo<V>::bar(); } }; template<class T> class Foo : aux<T> { // ... };
1,797,769
1,869,231
Recoloring an image based on current theme?
I want to develop a program which recolors the input image based on the given theme the same way as ms-powerpoint application does. I am giving following link that shows what exactly i want to do. I want to generate images same as images in below link under the Dark Variations and light Variations title based on the current theme. http://blogs.msdn.com/powerpoint/archive/2006/07/06/658238.aspx Can anybody give me idea,info regarding how to achieve it efficiently ??
I must say thanks to Mark and Patrice for ur guidance which helped me achieved it. For light variation, I have done it by converting the theme colors to HSV colorspace and found relation between output color and theme color for black color (input) . The relation was found to be linear for saturation and value and hue was almost constant. I have used interpolation formula to make it generic for any given theme. I have also make use of color matrix to achieve desired result. Similarly for dark variation i have used white color as input and apply the same technique.
1,798,112
1,798,170
Removing leading and trailing spaces from a string
How to remove spaces from a string object in C++. For example, how to remove leading and trailing spaces from the below string object. //Original string: " This is a sample string " //Desired string: "This is a sample string" The string class, as far as I know, doesn't provide any methods to remove leading and trailing spaces. To add to the problem, how to extend this formatting to process extra spaces between words of the string. For example, // Original string: " This is a sample string " // Desired string: "This is a sample string" Using the string methods mentioned in the solution, I can think of doing these operations in two steps. Remove leading and trailing spaces. Use find_first_of, find_last_of, find_first_not_of, find_last_not_of and substr, repeatedly at word boundaries to get desired formatting.
This is called trimming. If you can use Boost, I'd recommend it. Otherwise, use find_first_not_of to get the index of the first non-whitespace character, then find_last_not_of to get the index from the end that isn't whitespace. With these, use substr to get the sub-string with no surrounding whitespace. In response to your edit, I don't know the term but I'd guess something along the lines of "reduce", so that's what I called it. :) (Note, I've changed the white-space to be a parameter, for flexibility) #include <iostream> #include <string> std::string trim(const std::string& str, const std::string& whitespace = " \t") { const auto strBegin = str.find_first_not_of(whitespace); if (strBegin == std::string::npos) return ""; // no content const auto strEnd = str.find_last_not_of(whitespace); const auto strRange = strEnd - strBegin + 1; return str.substr(strBegin, strRange); } std::string reduce(const std::string& str, const std::string& fill = " ", const std::string& whitespace = " \t") { // trim first auto result = trim(str, whitespace); // replace sub ranges auto beginSpace = result.find_first_of(whitespace); while (beginSpace != std::string::npos) { const auto endSpace = result.find_first_not_of(whitespace, beginSpace); const auto range = endSpace - beginSpace; result.replace(beginSpace, range, fill); const auto newStart = beginSpace + fill.length(); beginSpace = result.find_first_of(whitespace, newStart); } return result; } int main(void) { const std::string foo = " too much\t \tspace\t\t\t "; const std::string bar = "one\ntwo"; std::cout << "[" << trim(foo) << "]" << std::endl; std::cout << "[" << reduce(foo) << "]" << std::endl; std::cout << "[" << reduce(foo, "-") << "]" << std::endl; std::cout << "[" << trim(bar) << "]" << std::endl; } Result: [too much space] [too much space] [too-much-space] [one two]
1,798,538
1,798,637
Looking for some refactoring advice
I have some code that I had to write to replace a function that was literally used thousands of times. The problem with the function was that return a pointer to a static allocated buffer and was ridiculously problematic. I was finally able to prove that intermittent high load errors were caused by the bad practice. The function I was replacing has a signature of char * paddandtruncate(char *,int), char * paddandtruncate(float,int), or char * paddandtruncat(int,int). Each function returned a pointer to a static allocated buffer which was overwritten on subsequent calls. I had three constants one the Code had to be replaceable with no impact on the callers. Very little time to fix the issue. Acceptable performance. I wanted some opinion on the style and possible refactoring ideas. The system is based upon fixed width fields padded with spaces, and has some architectural issues. These are not addressable since the size of the project is around 1,000,000 lines. I was at first planning on allowing the data to be changed after creation, but thought that immutable objects offered a more secure solution. using namespace std; class SYSTEM_DECLSPEC CoreString { private: friend ostream & operator<<(ostream &os,CoreString &cs); stringstream m_SS ; float m_FltData ; long m_lngData ; long m_Width ; string m_strData ; string m_FormatedData; bool m_Formated ; stringstream SS ; public: CoreString(const string &InStr,long Width): m_Formated(false), m_Width(Width), m_strData(InStr) { long OldFlags = SS.flags(); SS.fill(' '); SS.width(Width); SS.flags(ios::left); SS<<InStr; m_FormatedData = SS.str(); } CoreString(long longData , long Width): m_Formated(false), m_Width(Width), m_lngData(longData) { long OldFlags = SS.flags(); SS.fill('0'); SS.precision(0); SS.width(Width); SS.flags(ios::right); SS<<longData; m_FormatedData = SS.str(); } CoreString(float FltData, long width,long lPerprecision): m_Formated(false), m_Width(width), m_FltData(FltData) { long OldFlags = SS.flags(); SS.fill('0'); SS.precision(lPerprecision); SS.width(width); SS.flags(ios::right); SS<<FltData; m_FormatedData = SS.str(); } CoreString(const string &InStr): m_Formated(false), m_strData(InStr) { long OldFlags = SS.flags(); SS.fill(' '); SS.width(32); SS.flags(ios::left); SS<<InStr; m_FormatedData = SS.str(); } public: operator const char *() {return m_FormatedData.c_str();} operator const string& () const {return m_FormatedData;} const string& str() const ; }; const string& CoreString::str() const { return m_FormatedData; } ostream & operator<<(ostream &os,CoreString &cs) { os<< cs.m_Formated; return os; }
If you really do mean "no impact on the callers", your choices are very limited. You can't return anything that needs to be freed by the caller. At the risk of replacing one bad solution with another, the quickest and easiest solution might be this: instead of using a single static buffer, use a pool of them and rotate through them with each call of your function. Make sure the code that chooses a buffer is thread safe.
1,798,631
1,798,671
c++ vector of class object pointers
What I am trying to do is essentially create two vectors of objects, where some objects are entered into both lists and some are just entered into one. The first problem I found was that when I used push_back() to add an object into both lists the object was copied so that when I changed it from one list the object did not change in the other. To get around this I tried to create a list of pointers to objects as one of the lists. However when I accessed the pointer later on the data seemed to be corrupted, the data member values were all wrong. Here are some snippets of my code: Definition of vectors: vector<AbsorbMesh> meshList; vector<AbsorbMesh*> absorbList; ... Adding an object to both: AbsorbMesh nurbsMesh = nurbs.CreateMesh(uStride, vStride); // Add to the absorption list absorbList.push_back(&nurbsMesh); // Store the mesh in the scene list meshList.push_back(nurbsMesh); Accessing the object: if (absorbList.size() > 0) { float receivedPower = absorbList[0]->receivedPower; } What am I doing wrong?
There's some details missing, but at a guess. nurbsMesh goes out of scope between the push_back and the absorbList[0]->receivedPower. So now your vector of pointers contains a pointer to an object that doesn't exist anymore. Try adding a copy constructor to your AbsorbMesh class and adding to your vector like this. absorbList.push_back(new AbsorbMesh(nurbsMesh)); meshList.push_back(nurbsMesh); don't forget to delete the objects in absorbList, like this for(vector<AbsorbMesh*>::iterator it = absorbList.begin(); it != absorbList.end(); it++) { delete it; } Or store a shared pointer in your vector instead of a bare pointer. Boost has a good shared pointer implementation if you're interested. See the docs here If you want to have updates to items in one vector modify objects in the other vector, then you'll need to store pointers in both vectors. Using your original requirements (updating an item in one vector affects items in the other vector, here's how I'd do it with a boost shared pointer. (WARNING, untested code) vector<boost::shared_ptr<AbsorbMesh> > meshList; vector<boost::shared_ptr<AbsorbMesh> > absorbList; boost::shared_ptr<AbsorbMesh> nurb = new AbsorbMesh(nurbs.CreateMesh(uStride, vStride)); meshList.push_back(nurb); absorbList.push_back(nurb); ... ... if (absorbList.size() > 0) { float receivedPower = absorbList[0].get()->receivedPower; }
1,798,978
1,799,104
How to check if a file is a DLL?
Given a file, I want to check if this is a DLL, or a shared object (Linux) or a dylib (Mac OS X), or something different. My main interest is differentiating executable and DLL on Linux and Mac OS X. For windows, the extension should be enough for my problem. I already checked that the magic number technique doesn't work for Linux as executable and shared objects both have the same number.
The Unix (Linux and Mac OS X) command file knows how to identify file types. man file tells you about the 'magic' information used to do this, and in particular where the file with that information is to be found. man 5 magic describes the file in detail and should also tell you where it lives. You can take a look in there and pull anything you need from it. And/or just crib code from the source of file. Update: Note that on Linux a file could be both an executable and a shared library at the same time. One example is /lib/libc.so.6 (a shared library which can be executed). Another example: any executable built with -pie flag can be used as a shared library. See this answer for details.
1,799,063
1,799,310
How can I display unicode characters in a linux terminal using C++?
I'm working on a chess game in C++ on a linux environment and I want to display the pieces using unicode characters in a bash terminal. Is there any way to display the symbols using cout? An example that outputs a knight would be nice: ♞ = U+265E.
To output Unicode characters you just use output streams, the same way you would output ASCII characters. You can store the Unicode codepoint as a multi-character string: std::string str = "\u265E"; std::cout << str << std::endl; It may also be convenient to use wide character output if you want to output a single Unicode character with a codepoint above the ASCII range: setlocale(LC_ALL, "en_US.UTF-8"); wchar_t codepoint = 0x265E; std::wcout << codepoint << std::endl; However, as others have noted, whether this displays correctly is dependent on a lot of factors in the user's environment, such as whether or not the user's terminal supports Unicode display, whether or not the user has the proper fonts installed, etc. This shouldn't be a problem for most out-of-the-box mainstream distros like Ubuntu/Debian with Gnome installed, but don't expect it to work everywhere.
1,799,070
1,799,293
What might cause OpenGL to behave differently under the "Start Debugging" versus "Start without debugging" options?
I have written a 3D-Stereo OpenGL program in C++. I keep track of the position objects in my display should have using timeGetTime after a timeBeginPeriod(1). When I run the program with "Start Debugging" my objects move smoothly across the display (as they should). When I run the program with "Start without debugging" the objects occationally freeze for several screen refreshes then jump to a new position. Any ideas as to what may be causing this problem and how to fix it? Edit: It seems like the jerkiness can be resolved after a short delay when I run through "Start without debugging" if I click the mouse button. My application is a console application (I take in some parameters when the program first starts). Might there be a difference in window focus between these two options? Is there an explicit way to force the focus to the OpenGL window (in full screen through glutFullScreen();) when I'm done taking input from the console window? Thanks.
The most common thing that causes any program to behave differently while being debugged and not being debugged is using uninitialized variables and especially reading uninitialized memory. Check that you're not doing that. Something more OpenGL specific - You might have some problems with flushing of commands. Try inserting glFinish() after drawing every frame. It might also be helpful to somehow really make sure that when the freeze occurs there are actually frames being rendered and not that the whole application is frozen. If there are its more likely that you have some bug in the logic since it seems that OpenGL does its job.
1,799,072
1,799,077
C++ short-circuiting of booleans
I'm new to c++ and am curious how the compiler handles lazy evaluation of booleans. For example, if(A == 1 || B == 2){...} If A does equal 1, is the B==2 part ever evaluated?
No, the B==2 part is not evaluated. This is called short-circuit evaluation. Edit: As Robert C. Cartaino rightly points out, if the logical operator is overloaded, short-circuit evaluation does not take place (that having been said, why someone would overload a logical operator is beyond me).
1,799,157
1,799,165
Implicit type conversions in expressions int to double
I've been trying to reduce implicit type conversions when I use named constants in my code. For example rather than using const double foo = 5; I would use const double foo = 5.0; so that a type conversion doesn't need to take place. However, in expressions where I do something like this... const double halfFoo = foo / 2; etc. Is that 2 evaluated as an integer and is it implicitly converted? Should I use a 2.0 instead?
The 2 is implicitly converted to a double because foo is a double. You do have to be careful because if foo was, say, an integer, integer division would be performed and then the result would be stored in halfFoo. I think it is good practice to always use floating-point literals (e.g. 2.0 or 2. wherever you intend for them to be used as floating-point values. It's more consistent and can help you to find pernicious bugs that can crop up with this sort of thing.
1,799,445
1,799,531
Function template in non-template class
I'm sure that it is possible but I just can't do it, which is: How can I define function template inside non-template class? I tryied something like this: class Stack_T { private: void* _my_area; static const int _num_of_objects = 10; public: // Allocates space for objects added to stack explicit Stack_T(size_t); virtual ~Stack_T(void); // Puts object onto stack template<class T> void put(const T&); // Gets last added object to the stack template<class T> T& get()const; // Removes last added object from the stack template<class T> void remove(const T&); }; template<class T> //SOMETHING WRONG WITH THIS DEFINITION void Stack_T::put<T>(const T& obj) { } but it doesn't work. I'm getting this err msg: 'Error 1 error C2768: 'Stack_T::put' : illegal use of explicit template arguments' Thank you
Don't put the <T> after the function name. This should work: template<class T> void Stack_T::put(const T& obj) { } This still won't work if the function definition is not in the header file. To solve this, use one of: Put the function definition in the header file, inside the class. Put the function definition in the header file after the class (like in your example code). Use explicit template instanciation in the header file. This has serious limitations though (you have to know all possible values of T in advance).
1,799,497
1,799,503
C++ overloaded function issue
Why does the compiler not find the base class function signature? Changing foo( a1 ) to B::foo( a1 ) works. Code: class A1 ; class A2 ; class B { public: void foo( A1* a1 ) { a1 = 0 ; } } ; class C : public B { public: void foo( A2* /*a2*/ ) { A1* a1 = 0 ; foo( a1 ) ; } } ; int main() { A2* a2 = 0 ; C c ; c.foo( a2 ) ; return 0 ; } Compiler error (VS2008): error C2664: 'C::foo' : cannot convert parameter 1 from 'A1 *' to 'A2 *' Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
The name C::foo shadows the name B::foo. Once the compiler finds the matching foo in class C, it stops searching any further. You can resolve your problem by adding: using B::foo; to the body of class C, or by renaming the function in class B.
1,799,507
1,799,532
Combo box inside of list control? (Unmanaged C++)
I'm using unmanaged C++ and I was wondering if I could embed a combo box inside a column of my List View. I have tried googling for information, however I keep finding C# articles on the subject. It seems like the LVCOLUMN's mask can support text and images but I am not finding anything about controls. Any ideas on the subject would be great.
You can create a floating combo box and position it over the selected row and column of the list control. You'll need to trap all selection related operations on the list control and show, hide, or move and update the contents of the combo box.
1,799,664
1,799,906
Passing Exception Types down through a menu
So I've come across this problem and I can't seem to solve it. Basically I've got a menu of tests, it can be of arbitrary depth, it's just a way of organizing tests and at the lowest level has specific test-cases. As it stands right now everything seems to work, however I'd like to implement a system where you can specify an exception type and act on whether or not it gets thrown. To complicate things more, due to some macros we're using the catch block takes only the type, not an instance (which I believe a normal catch can, it's been a while). so here's some code as it is now: Adding a test: Menu* mainmenu = new Menu("MainMenu"); Menu* sub1 = mainmenu->add("Sub1", functionptr); sub1->add("Test1", "Script_to_Drive_Test"); sub1->add("Test2", "Script_to_Drive_Test"); sub1->add("Test3", "Script_to_Drive_Test"); What I'd like is to be able to specify an exception like so: .... sub1->add<SOME::EXCEPTION1>("Test1", "Script_to_Drive_Test"); sub1->add<SOME::EXCEPTION2>("Test2", "Script_to_Drive_Test"); sub1->add<SOME::EXCEPTION3>("Test3", "Script_to_Drive_Test"); The issue is that there's multiple exceptions to test for, which (I believe) creates different types. Currently everything gets stored cleanly in a vector when add is called, however using templates that's no longer possible (even if I were to templatize the vector type as well, it wouldn't work after the first exception is created, since Test2 and Test3 are of a different type, right?). In reality there are a ton of different exceptions to test for. So the core issue I'm having is being able to get those exception types down into the bowls of my menu. A complete re-write isn't out of the question (it's a relatively small system), however I'd really prefer not to. Any insight/help or even questions would be greatly appreciated. I'd be more than happy to clarify anything.
I'm not sure if I understand your question well. However as far as I understood your problem is that now add creates an object depending on the specified exception type and thous you cannot store it in internal vector. You might try to use a common base class. Make the vector store a pointer to non-template base class while each add will create an object of derived template class (the template depends on the exception type passed to add). In general all operations performed previously on the objects stored in vector will now be virtual functions on the base class implemented in the derived template class.
1,799,697
1,799,720
New not allocating enough memory?
Well, I'm taking packets straight off the wire and extracting TCP streams from them. In the short, this means stripping off the various headers (eg, eth->IP->TCP->stream data). In the function that is called when I've finally gotten through all the headers, I am experiencing a strange error. /*Meta is a pointer to the IP header, pkt is a pointer to the TCP header*/ virtual const u_char* processPacket(const u_char* pkt, const u_char* meta) { //Extract IP info from meta. iphdr* metaHdr = (iphdr*)meta; //Form TCP header from the current offset, hdr. const tcphdr* hdr = (const tcphdr*)pkt; //Do pointer math to figure out the size of the stream data. u_int32_t len = ntohs(metaHdr->tot_len) - metaHdr->ihl*4 - hdr->doff*4; if(len > 0) { //Store TCP stream data in a queue, mapped to it's IP source. TCPStream* stream = new TCPStream(); stream->seqNumber = ntohl(hdr->seq); stream->streamData = new u_char(len); //memcpy(stream->streamData, offset(pkt), len); for(u_int32_t i = 0; i < len; i++) { printf("k%i-%i",len, i); //Used to figure out when the segfault occurs. stream->streamData[i] = offset(pkt)[i]; //Offset returns a pointer to the data under the TCP header } //streams[metaHdr->saddr].push(stream); } return offset(pkt); }; TCP stream is simply a u_int32_t and a u_char* pointing to a copy of the packet's data. So, when I was using memcpy it segfaulted. Obviously, either my pointers were invalid, or I was messing up my length. In this particular packet's case, the length of the data is 1380 bytes (confirmed by Wireshark), so len is correctly computed. Ok, so I must have my pointers messed up (but not NULL). I did the following experiment: stream->streamData[0] = offset(pkt)[0]; //Works stream->streamData[0] = offset(pkt)[len]; //Works, odd. stream->streamData[len] = offset(pkt)[0]; //Fails, scary stream->streamData[len] = offset(pkt)[len]; //Fails So, I segfault when dereferencing too far into streamData (index 1236 to be specific)! But streamData is instantiated as: stream->streamData = new u_char(len); I start iterating through streamData at i=0, so I'm not skipping a bunch of my data. streamData is u_char* and offset(pkt) is u_char* so I'm not messing up my types. This fails at a particular packet, after successfully iterating through 3000+ other packets. The dump file is 27 megs, and I've got 4 gigs of ram, so I don't think I'm running out or anything... So I'm forced to conclude that new is not allocating enough memory, but why?
stream->streamData = new u_char(len); This allocates a single character, intialized to len. To allocate an array, use: stream->streamData = new u_char[len]; And where-ever you deallocate it: delete [] stream->streamData; Edit: stream->streamData[len] = offset(pkt)[0]; //Fails, scary That would be undefined behavior even if the array was allocated correctly. Valid indexes to access are 0 to len not inclusive.
1,799,733
1,799,744
foreach algorithm in C++
Is there a way to have a return value from the function that I pass to foreach. For ex: I have, void myfunction (int i) { cout << " " << i; } vector<int> myvector; myvector.push_back(10); for_each (myvector.begin(), myvector.end(), myfunction); Lets say, I want to count the number of elements in the vector using some rule, I want to have a return value from myFunction, is this possible?
No. But you can make myfunction a functor, pass it a pointer to some memory, and store your return value through that pointer. struct MyFunctor { int *count; MyFunctor(int *count_) : count(count_) { } void operator()(int n) { if (n > 5) (*count)++; } }; int main() { vector<int> vec; for (int i=0; i<10; i++) vec.push_back(i); int count = 0; for_each(vec.begin(), vec.end(), Myfunctor(&count)); printf("%d\n", count); return 0; } Edit: As the comments have pointed out, my first example would've failed as for_each would have made a copy of MyFunctor, so we couldn't have retrieved the return value from our original object. I've fixed along the lines of the original approach; but you really should look at GMan's solution which is more elegant. I'm not sure about the portability, but it does work on my gcc (4.4.2). And as the others have mentioned, whenever possible, use what <algorithm> provides.
1,799,737
1,799,804
Benefits of opening a file for read and write
Can anyone point me to some discussion covering the pro's and con's of opening a file for read and write as opposed to (for example) opening a file for read, closing it and then reopening for write. I've tried searching for in-depth information without joy. Many thanks
It depends on what you're doing. Opening for read and write can be harder to get correct and consistent as it's very easy to accidentally truncate the file or overwrite parts of the data unintentionally. If reading and then writing (presumably a complete replacement) is actually an option, then two separate file opens may well be simpler, but consider writing to a new file and renaming if successful to make sure that if something (even a programming error!) interrupts the write the old data isn't lost. If you do decide to open for read/write make sure to read the documentation carefully so that you don't truncate the file on opening and take care with seek and tell functions. Unless you open in binary mode you can only safely pass to seek a position that was returned by a previous tell.
1,800,138
1,800,193
Given a start and end point, and a distance, calculate a point along a line
Looking for the quickest way to calculate a point that lies on a line a given distance away from the end point of the line: void calculate_line_point(int x1, int y1, int x2, int y2, int distance, int *px, int *py) { //calculate a point on the line x1-y1 to x2-y2 that is distance from x2-y2 *px = ??? *py = ??? } Thanks for the responses, no this is not homework, just some hacking out of my normal area of expertise. This is the function suggested below. It's not close to working. If I calculate points every 5 degrees on the upper right 90 degree portion of a circle as starting points and call the function below with the center of the circle as x2,y2 with a distance of 4 the end points are totally wrong. They lie below and to the right of the center and the length is as long as the center point. Anyone have any suggestions? void calculate_line_point(int x1, int y1, int x2, int y2, int distance) { //calculate a point on the line x1-y1 to x2-y2 that is distance from x2-y2 double vx = x2 - x1; // x vector double vy = y2 - y1; // y vector double mag = sqrt(vx*vx + vy*vy); // length vx /= mag; vy /= mag; // calculate the new vector, which is x2y2 + vxvy * (mag + distance). px = (int) ( (double) x2 + vx * (mag + (double)distance) ); py = (int) ( (double) y2 + vy * (mag + (double)distance) ); } I've found this solution on stackoverflow but don't understand it completely, can anyone clarify?
I think this belongs on MathOverflow, but I'll answer since this is your first post. First you calculate the vector from x1y1 to x2y2: float vx = x2 - x1; float vy = y2 - y1; Then calculate the length: float mag = sqrt(vx*vx + vy*vy); Normalize the vector to unit length: vx /= mag; vy /= mag; Finally calculate the new vector, which is x2y2 + vxvy * (mag + distance). *px = (int)((float)x1 + vx * (mag + distance)); *py = (int)((float)y1 + vy * (mag + distance)); You can omit some of the calculations multiplying with distance / mag instead.
1,800,250
1,800,466
Is there a better way to create this game loop? (C++/Windows)
I'm working on a Windows game, and I have this: bool game_cont; LRESULT WINAPI WinProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_QUIT: case WM_CLOSE: case WM_DESTROY: game_cont = false; break; } return DefWindowProc(hWnd, msg, wParam, lParam); } int WINAPI WinMain(/*lots of parameters*/) { //tedious initialization //game loop while(game_cont) { //give message to WinProc if(!GameRun()) game_cont = false; } return 0; } and I am wondering if there is a better way to do this (ignoring timers &c. for right now) than to have game_cont be global. In short, I need to be able to exit the while in WinMain from WinProc, so that if the user presses the closes out of the game in a way other that the game's in game menu, the program wont keep running in memory. (As it did when I tested this without the game_cont.. statement in WinProc. Oh, and on a side note, GameRun is basically a bool that returns false when the game ends, and true otherwise.
Yes, use PeekMessage, it's the standard in game development. This is the best approach, I believe: int Run() { MSG msg; while(true) { if(::PeekMessage(&msg,0,0,0 PM_REMOVE)) { if(msg.message == WM_QUIT || msg.message == WM_CLOSE || msg.message == WM_DESTROY) break; ::TranslateMessage(&msg); ::DispatchMessage(&msg); } else { //Run game code if(!GameRun()) break; } } } Also, look at this (specially the first answer)
1,800,423
1,800,464
What is the performance penalty of operator overloading STL
I like STL a lot. It makes coding algorithms very convenient since it provides you will all the primitives like parition, find, binary_search, iterators, priority_queue etc. Plus you dont have to worry about memory leaks at all. My only concern is the performance penalty of operator overloading that is necessary to get STL working. For comparison, I think it relies that == provides the needed semantics. We need to overload ==operator if we are adding our classes to a container. How much efficiency am I losing for this convenience? Another aside question regarding memory leaks: Can memory leak ever happen when using STL containers? Can a memory leak ever happen in Java?
When using stl algortithms on generic types, you have to supply the comparison logic in some way. Operator overloading has no performance penalty over any other function and may (like any other function) be inlined to remove any function call overhead. Many standard containers and algorithms also use std::less and hence by default < rather than ==. The standard containers don't themselves leak, but you can use them to hold objects (such as pointers) which don't necessarily clean up memory that they 'own'. It's difficult to leak memory in java, but that doesn't mean you can't get into trouble by failing to have good object ownership semantics and it doesn't mean that you can't use up all the available memory and crash.
1,800,544
1,803,799
Are there well-defined size limits in FormatMessage?
I am having a problem when arguments passed to FormatMessage are too long. void testMessage(UINT id, ...) { va_list argList; va_start(argList, id); LPTSTR buff = NULL; const char* str = "The following value is invalid: %1"; DWORD success = FormatMessage(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ALLOCATE_BUFFER, str, 0, 0, (LPSTR) &buff, 0, &argList); if(0 == success) { DWORD err = GetLastError(); //... } va_end(argList); //... } int main(int argc, char** argv) { const char* arg = NULL; // ... // Initialize arg to some big string about 33,000 bytes long. // ... test(0, arg); } The error I get is ERROR_MORE_DATA (234). When I reduce the size of arg to about 32,000 bytes, the problem doesn't occur, but it's unclear whether the restriction has to do with the size of arguments passed in or the resulting total size of the string generated. The MSDN page on FormatMessage says about the lpBuffer parameter, "This buffer cannot be larger than 64K bytes." I can easily get around this by doing a bit more error checking and putting some sane restrictions on the size of the arguments I pass into this function, but for my and others' future reference it would be great to know what the real limits are.
Are you calling FormatMessageA or FormateMessageW ? If you call FormatMessageA, your 32K ASCII message will be marshalled to a 64K Unicode message. Windows today is internally Unicode, and the "A" series of functions are just wrappers around the "W" functions.
1,800,875
1,800,890
Convert single char to int
How can I convert char a[0] into int b[0] where b is a empty dynamically allocated int array I have tried char a[] = "4x^0"; int *b; b = new int[10]; char temp = a[0]; int temp2 = temp - 0; b[0] = temp2; I want 4 but it gives me ascii value 52 Also doing a[0] = atoi(temp); gives me error: invalid conversion from ‘char’ to ‘const char*’ initializing argument 1 of ‘int atoi(const char*)’
You need to do: int temp2 = temp - '0'; instead.
1,800,886
1,826,446
Strange error with hardware picking in directx
i am trying to get pickigng working in directx 9 and i am having some trouble. it works fine when i am rendering my mesh in software however i do get errors when rendering with a shader. i can be off of a mesh but it still detects it as a hit (see image for more detail) i am stopping animation controllers and updating frame matrices but still no joy with the picking. http://tweetphoto.com/a7vtajzt any help much apprechiated this has been driving me nuts for two days now. regards Mark
not to worry i found out that i was missing a clone function that i was doing in software mode but not hardware
1,800,983
1,801,055
c++ server htons to java ntohs client conversion
I am creating a small TFTP client server app where server is developed using c++ and client using java. Here i am sending "block count" value using htons conversion. But i am not able to convert it back to its original value at client. For example if am sending block count ntohs(01) (2 bytes) from server to client. Client is reading in bytes. Value which I am receiving is byte 0 and byte 1. Please if any one can provide a solution.
I take it you meant that you use ntohs to decode the values read from the network, and htons to encode the values sent over the network. Look into ByteBuffer#getShort() in concert with ByteBuffer#order(ByteOrder). Network byte order is big endian, so use the value ByteOrder#BIG_ENDIAN to configure your ByteBuffer properly. Note that BIG_ENDIAN is the default order, but in this case it would be good form to state your preference explicitly. You didn't mention what you're using for network communications in Java. If it's a java.net.Socket, you can call Socket#getChannel() to get a java.nio.channels.SocketChannel, a subtype of java.nio.channels.ByteChannel, with which you can use ByteBuffer to read and write data.
1,801,220
1,801,234
C tokenize polynomial coefficients
I'm trying to put the coefficients of polynomials from a char array into an int array I have this: char string[] = "-4x^0 + x^1 + 4x^3 - 3x^4"; and can tokenize it by the space into -4x^0 x^1 4x^3 3x^4 So I am trying to get: -4, 1, 4, 3 into an int array int *coefficient; coefficient = new int[counter]; p = strtok(copy, " +"); int a; while (p) { int z = 0; while (p[z] != 'x') z++; char temp[z]; strncpy(temp[z], p, z); coefficient[a] = atoi(temp); p = strtok(NULL, " +"); a++; } However, Im getting an error that I cant convert a char* into a char on strncpy(temp[z], p, z); error: invalid conversion from ‘char’ to ‘char*’ error: initializing argument 1 of ‘char* strncpy(char*, const char*, size_t)’ What would be the best way to do this?
This: strncpy(temp[z], p, z); Needs to be: strncpy(temp, p, z); But remember that strncpy doesn't always null-terminate the string. Also, z will be the length of the coefficient, but you need an extra byte in the buffer for the null terminator. Update: examining your link, I still see several serious problems: You can't use "-" in strtok because it will pick up the one in "-4x" as well as the ones you want. I think you should split on spaces only and handle the +/- operators as tokens. The strncpy function leaves the string un-terminated, which may cause atoi to crash or give the wrong value randomly. One idiomatic form is to write the terminator manually, e.g., temp[z] = '\0'. The reason you're not getting any output values is that coefficient[a] = is writing to some random memory because a is uninitialized.
1,801,251
1,801,280
Modifying contents of vector in BOOST_FOREACH
This is a question that goes to how BOOST_FOREACH checks it's loop termination cout << "Testing BOOST_FOREACH" << endl; vector<int> numbers; numbers.reserve(8); numbers.push_back(1); numbers.push_back(2); numbers.push_back(3); cout << "capacity = " << numbers.capacity() << endl; BOOST_FOREACH(int elem, numbers) { cout << elem << endl; if (elem == 2) numbers.push_back(4); } cout << "capacity = " << numbers.capacity() << endl; gives the output Testing BOOST_FOREACH capacity = 8 1 2 3 capacity = 8 But what about the number 4 which was inserted half way through the loop? If I change the type to a list the newly inserted number will be iterated over. The vector push_back operation will invalidate any pointers IF a reallocation is required, however that is not happening in this example. So the question I guess is why does the end() iterator appear to only be evaluated once (before the loop) when using vector but has a more dynamic evaluation when using a list?
Under the covers, BOOST_FOREACH uses iterators to traverse the element sequence. Before the loop is executed, the end iterator is cached in a local variable. This is called hoisting, and it is an important optimization. It assumes, however, that the end iterator of the sequence is stable. It usually is, but if we modify the sequence by adding or removing elements while we are iterating over it, we may end up hoisting ourselves on our own petard. http://www.boost.org/doc/libs/1_40_0/doc/html/foreach/pitfalls.html If you don't want the end() iterator to change use resize on the vector rather than reserve. http://www.cplusplus.com/reference/stl/vector/resize/ Note that then you wouldn't want to push_back but use the operator[] instead. But be careful of going out of bounds.
1,801,258
1,836,063
Does using __declspec(novtable) on abstract base classes affect RTTI in any way?
Or, are there any other known negative affects of employing __declspec(novtable)? I can't seem to find references to any issues.
MSCV uses one vptr per object and one vtbl per class to implement OO mechanism such as RTTI and virtual functions. So RTTI and virtual functions will work fine if and only if the vptr has been set correctly. struct __declspec(novtable) B { virtual void f() = 0; }; struct D1 : B { D1() { } // after the construction of D1, vptr will be set to vtbl of D1. }; D1 d1; // after d has been fully constructed, vptr is correct. B& b = d1; // so virtual functions and RTTI will work. b.f(); // calls D1::f(); assert( dynamic_cast<D1*>(&b) ); assert( typeid(b) == typeid(D1) ); B should be an abstract class when use __declspec(novtable). There will be no instance of B except in the constructor of D1. And __declspec(novtable) has no negative affects in most case. But during the construction of derived class __declspec(novtable) will make it different from ISO C++ semantic. struct D2 : B { D2() { // when enter the constructor of D2 \ // the vtpr must be set to vptr of B \ // if B didn't use __declspec(novtable). // virtual functions and RTTI will also work. this->f(); // should calls B::f(); assert( typeid(*this) == typeid(B) ); assert( !dynamic_cast<D2*>(this) ); assert( dynamic_cast<B*>(this) ); // but __declspec(novtable) will stop the compiler \ // from generating code to initialize the vptr. // so the code above will crash because of uninitialized vptr. } }; Note: virtual f() = 0; makes f to be a pure virtual function and B to be an abstract class. The definition of a pure virtual function could (not must) be missing. C++ allows virtual function call in constructor which we don't recommend. Update: A mistake in D2 : the vptr in derived constructor. struct D3 : B { // ISO C++ semantic D3() { // vptr must be set to vtbl of B before enter } // vptr must be set to vtbl of D2 after leave }; But vptr is indeterminate during the construction.It's one of the reason that virtual function call in constructor aren't recommend . If vptr in D2::D2() was B and definition of B::f() was missing, this->f(); will crash when dereference pointer-to-function in the vtbl. If vptr in D2::D2() was B and B use novtable, this->f(); will crash when dereference an uninitialized vptr. In fact , vptr in D2::D2() is D2 in MSVC(msvc8).The compiler set vptr to D2 before execute other code in D2::D2(). So this->f(); calls D2::f() and the three assertions will be violated.
1,801,363
1,801,402
C/C++: any way to get reflective enums?
I've encountered this situation so many times... enum Fruit { Apple, Banana, Pear, Tomato }; Now I have Fruit f; // banana and I want to go from f to the string "Banana"; or I have string s = "Banana" and from that I want to go to Banana // enum value or int. So far I've been doing this.. Assuming the enum is in Fruit.h: // Fruit.cpp const char *Fruits[] = { "Apple", "Banana", "Pear", "Tomato", NULL }; Obviously that's a messy solution. If a developer adds a new fruit to the header and doesn't add a new entry in Fruits[] (can't blame him, they have to be in two different files!) the application goes boom. Is there a simple way to do what I want, where everything is in one file? Preprocessor hacks, alien magic, anything.. PS: This, contrary to reflection "for everything", would be really trivial to implement in compilers. Seeing how common a problem it is (at least for me) I really can't believe there is no reflective enum Fruit.. Not even in C++0x. PS2: I'm using C++ but I tagged this question as C as well because C has the same problem. If your solution includes C++ only things, that's ok for me.
This one requires the fruits to be defined in an external file. This would be the content of fruit.cpp: #define FRUIT(name) name enum Fruit { #include "fruit-defs.h" NUM_FRUITS }; #undef FRUIT #define FRUIT(name) #name const char *Fruits [] = { #include "fruit-defs.h" NULL }; #undef FRUIT And this would be fruit-defs.h: FRUIT(Banana), FRUIT(Apple), FRUIT(Pear), FRUIT(Tomato), It works as long as the values start in 0 and are consecutive... Update: mix this solution with the one from Richard Pennington using C99 if you need non-consecutive values. Ie, something like: // This would be in fruit-defs.h FRUIT(Banana, 7) ... // This one for the enum #define FRUIT(name, number) name = number .... // This one for the char *[] #define FRUIT(name, number) [number] = #name
1,801,389
1,801,395
Why no compiler enforcement in const_iterator
Consider the following code : #include <vector> #include <iostream> class a { public: int i; void fun() { i = 999; } void fun() const { std::cout << "const fun" << std::endl; } }; const a* ha() { return new a(); } int main() { std::vector<a *> v; v.push_back(new a()); // cannot convert from 'const a *' to 'a *' // a* test = ha(); std::vector<a *>::const_iterator iterator = v.begin(); for (; iterator != v.end(); ++iterator) { // No enforcement from compiler? I do not want user to modify the content through // const_iterator. a* aa = (*iterator); aa->fun(); } std::cout << (*(v.begin()))->i << std::endl; getchar(); } May I know why I didn't get compiler error from a* aa = (*iterator); I wish compiler will tell me I need to use the const_iterator in the following way : const a* aa = (*iterator); Or, this is my wrong expectation on const_iterator?
The const_iterator says that you can't modify the element in the container; that is, if you have a container of pointers, you can't change the pointer. You aren't changing the pointer, you're changing the object pointed to by the pointer. If you try to assign a new pointer to that element in the container, it will fail to compile: *iterator = new a; // < Won't compile
1,801,459
1,801,471
Algorithm - How to delete duplicate elements in a list efficiently?
There is a list L. It contains elements of arbitrary type each. How to delete all duplicate elements in such list efficiently? ORDER must be preserved Just an algorithm is required, so no import any external library is allowed. Related questions In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique while preserving order? How do you remove duplicates from a list in Python whilst preserving order? Removing duplicates from list of lists in Python How do you remove duplicates from a list in Python?
Assuming order matters: Create an empty set S and an empty list M. Scan the list L one element at a time. If the element is in the set S, skip it. Otherwise, add it to M and to S. Repeat for all elements in L. Return M. In Python: >>> L = [2, 1, 4, 3, 5, 1, 2, 1, 1, 6, 5] >>> S = set() >>> M = [] >>> for e in L: ... if e in S: ... continue ... S.add(e) ... M.append(e) ... >>> M [2, 1, 4, 3, 5, 6] If order does not matter: M = list(set(L))
1,801,509
1,804,937
Speeding up self-similarity in an image
I'm writing a program that will generate images. One measurement that I want is the amount of "self-similarity" in the image. I wrote the following code that looks for the countBest-th best matches for each sizeWindow * sizeWindow window in the picture: double Pattern::selfSimilar(int sizeWindow, int countBest) { std::vector<int> *pvecount; double similarity; int match; int x1; int x2; int xWindow; int y1; int y2; int yWindow; similarity = 0.0; // (x1, y1) is the original that's looking for matches. for (x1 = 0; x1 < k_maxX - sizeWindow; x1++) { for (y1 = 0; y1 < k_maxY - sizeWindow; y1++) { pvecount = new std::vector<int>(); // (x2, y2) is the possible match. for (x2 = 0; x2 < k_maxX - sizeWindow; x2++) { for (y2 = 0; y2 < k_maxY - sizeWindow; y2++) { // Testing... match = 0; for (xWindow = 0; xWindow < sizeWindow; xWindow++) { for (yWindow = 0; yWindow < sizeWindow; yWindow++) { if (m_color[x1 + xWindow][y1 + yWindow] == m_color[x2 + xWindow][y2 + yWindow]) { match++; } } } pvecount->push_back(match); } } nth_element(pvecount->begin(), pvecount->end()-countBest, pvecount->end()); similarity += (1.0 / ((k_maxX - sizeWindow) * (k_maxY - sizeWindow))) * (*(pvecount->end()-countBest) / (double) (sizeWindow * sizeWindow)); delete pvecount; } } return similarity; } The good news is that the algorithm does what I want it to: it will return a value from 0.0 to 1.0 about how 'self-similar' a picture is. The bad news -- as I'm sure that you've already noted -- is that the algorithm is extremely slow. It takes (k_maxX - sizeWindow) * (k_maxY - sizeWindow) * (k_maxX - sizeWindow) * (k_maxY - sizeWindow) * sizeWindow * sizeWindow steps for a run. Some typical values for the variables: k_maxX = 1280 k_maxY = 1024 sizeWindow = between 5 and 25 countBest = 3, 4, or 5 m_color[x][y] is defined as short m_color[k_maxX][k_maxY] with values between 0 and 3 (but may increase in the future.) Right now, I'm not worried about the memory footprint taken by pvecount. Later, I can use a sorted data set that doesn't add another element when it's smaller than countBest. I am only worried about algorithm speed. How can I speed this up?
Your problem strongly reminds me of the calculations that have to be done for motion compensation in video compression. Maybe you should take a closer look what's done in that area. As rlbond already pointed out, counting the number of points in a window where the colors exactly match isn't what's normally done in comparing pictures. A conceptually simpler method than using discrete cosine or wavelet transformations is to add the squares of the differences diff = (m_color[x1 + xWindow][y1 + yWindow] - m_color[x2 + xWindow][y2 + yWindow]); sum += diff*diff; and use sum instead of match as criterion for similarity (now smaller means better). Back to what you really asked: I think it is possible to cut down the running time by the factor 2/sizeWindow (maybe squared?), but it is a little bit messy. It's based on the fact that certain pairs of squares you compare stay almost the same when incrementing y1 by 1. If the offsets xOff = x2-x1 and yOff = y2-y1 are the same, only the top (rsp. bottom) vertical stripes of the squares are no longer (rsp. now, but not before) matched. If you keep the values you calculate for match in a two-dimensional array indexed by the offsets xOff = x2-x1 and yOff = y2-y1, then can calculate the new value for match[xOff][yOff] for y1 increased by 1 and x1 staying the same by 2*sizeWindow comparisons: for (int x = x1; x < x1 + sizeWindow; x++) { if (m_color[x][y1] == m_color[x + xOff][y1 + yOff]) { match[xOff][yOff]--; // top stripes no longer compared } if (m_color[x][y1+sizeWindow] == m_color[x + xOff][y1 + sizeWindow + yOff]) { match[xOff][yOff]++; // bottom stripe compared not, but wasn't before } } (as the possible values for yOff changed - by incrementing y1 - from the interval [y2 - y1, k_maxY - sizeWindow - y1 - 1] to the interval [y2 - y1 - 1, k_maxY - sizeWindow - y1 - 2] you can discard the matches with second index yOff = k_maxY - sizeWindow - y1 - 1 and have to calculate the matches with second index yOff = y2 - y1 - 1 differently). Maybe you can also keep the values by how much you increase/decrease match[][] during the loop in an array to get another 2/sizeWindow speed-up.
1,801,834
1,801,888
STL container's read-only operations
Need advice here: which of the STL container's operations are considered read-only? Take vector<int> as example, would it be safe to say that any operation that does not alter the underlying int data is read-only? I am writing a multi-threaded program, but not too sure if it is thread-safe to pass container by reference/pointer. Between, will the same rules apply to basic_string as well? Any recommended resource that helps for quickly gaining understanding on internal mechanism of STL container? Thanks.
Methods declared const most likely won’t modify the container, although you can’t be sure. When using STL containers in a multithreaded application you will need an external synchronization mechanism. The C++ standard library is not thread safe, and any use from multiple threads without synchronization will result in undefined behavior, assuming that one of the threads change the state of the vector object.
1,801,880
1,801,977
Selection between ACE & Boost for learning
I am an intermediate c++ programmer and done some work using ACE, now I want to learn one of those Libraries thoroughly to progress in to my career. That why I need your kind help to make a decision, that what should I learn first. And also please consider my destinations are to be an expert network programmer and Protocol designer. Thanks for your time and kind answers in advance.
This might not be the answer you're looking for, but I would strongly suggest that you don't artificially restrict yourself too much when it comes to career goals. Figure out how long you do expect your career as a programmer to continue and then ask yourself if you (a) can really see yourself doing network programming only for that amount of time and (b) if you well and truly believe that the one library you select for your in-depth knowledge will be able to fulfil the needs you have now for the rest of your career, without stagnating your career. What will sustain your programming career in the long term is not the in-depth knowledge of a single library or two, but your overall ability as a programmer. Libraries are tools (unless you are a library designer) in the same way that programming languages are tools (unless you are a language designer) and one mark of a good programmer is her or his abilities to select the appropriate tool for the task. With all that out of the way, I do recommend that every C++ programmer is at least familiar with the fact that boost exists and some of the core libraries like the smart pointer library, regular expressions etc. I would not expect anybody working for me to be an expert in all facets of Boost but I do expect even fairly inexperienced C++ programmers to know where they can find it and that they will be better off using code from Boost rather than trying to, say, write their own pooled memory allocator. The examples I gave might not look like they are directly applicable to network programming in the most narrow sense but they will certainly be needed in most programs of a non-trivial size. Another good reason to keep up with Boost is that a lot of the techniques that eventually will/might make it into the C++ standard library originate from Boost. Keeping an on where Boost is going will allow you to keep an eye on certain developments in the C++ community as new usage idioms are still being developed in C++; the language and its canonical usage is not "fixed", at least not as of now, and again this is something you will have to keep up with if you are planning on a longer term career as a C++ programmer.
1,801,892
1,801,913
How can I make the map::find operation case insensitive?
Does the map::find method support case insensitive search? I have a map as follows: map<string, vector<string> > directory; and want the below search to ignore case: directory.find(search_string);
It does not by default. You will have to provide a custom comparator as a third argument. Following snippet will help you... /************************************************************************/ /* Comparator for case-insensitive comparison in STL assos. containers */ /************************************************************************/ struct ci_less : std::binary_function<std::string, std::string, bool> { // case-independent (ci) compare_less binary function struct nocase_compare : public std::binary_function<unsigned char,unsigned char,bool> { bool operator() (const unsigned char& c1, const unsigned char& c2) const { return tolower (c1) < tolower (c2); } }; bool operator() (const std::string & s1, const std::string & s2) const { return std::lexicographical_compare (s1.begin (), s1.end (), // source range s2.begin (), s2.end (), // dest range nocase_compare ()); // comparison } }; Use it like std::map< std::string, std::vector<std::string>, ci_less > myMap; NOTE: std::lexicographical_compare has some nitty-gritty details. String comparison isn't always straightforward if you consider locales. See this thread on c.l.c++ if interested. UPDATE: With C++11 std::binary_function is deprecated and is unnecessary as the types are deduced automatically. struct ci_less { // case-independent (ci) compare_less binary function struct nocase_compare { bool operator() (const unsigned char& c1, const unsigned char& c2) const { return tolower (c1) < tolower (c2); } }; bool operator() (const std::string & s1, const std::string & s2) const { return std::lexicographical_compare (s1.begin (), s1.end (), // source range s2.begin (), s2.end (), // dest range nocase_compare ()); // comparison } };
1,801,949
1,801,955
How can a C++ base class determine at runtime if a method has been overridden?
The sample method below is intended to detect whether or not it has been overridden in a derived class. The error I get from MSVC implies that it is simply wrong to try to get the function pointer to a "bound" member, but I see no logical reason why this should be a problem (after all, it will be in this->vtable). Is there any non-hacky way of fixing this code? class MyClass { public: typedef void (MyClass::*MethodPtr)(); virtual void Method() { MethodPtr a = &MyClass::Method; // legal MethodPtr b = &Method; // <<< error C2276: ‘&’ : illegal operation on bound member function expression if (a == b) // this method has not been overridden? throw “Not overridden”; } };
There is no way to determine if a method has been overridden, except for pure virtual methods: they must be overridden and non-pure in a derived class. (Otherwise you can't instantiate an object, as the type is still "abstract".) struct A { virtual ~A() {} // abstract bases should have a virtual dtor virtual void f() = 0; // must be overridden } You can still provide a definition of the pure virtual method, if derived classes may or must call it: void A::f() {} Per your comment, "If the method had not been overridden it would mean it is safe to try mapping the call to the other method instead." struct Base { void method() { do_method(); } private: virtual void do_method() { call_legacy_method_instead(); } }; struct Legacy : Base { }; struct NonLegacy : Base { private: virtual void do_method() { my_own_thing(); } }; Now, any derived class may provide their own behavior, or the legacy will be used as a fallback if they don't. The do_method virtual is private because derived classes must not call it. (NonLegacy may make it protected or public as appropriate, but defaulting to the same accessibility as its base class is a good idea.)
1,802,059
1,802,081
Why does this pointer to C++ function code generate a compile error?
Can anyone solve this? I can’t seem to find the solution anywhere, but I see no logical reason why the line below (with the comment showing the compile error) should be a problem. Note: This question is a derivative of How can a C++ base class determine at runtime if a method has been overridden? class MyClass { typedef void (MyClass::*MethodPtr)(); virtual void Method() { MethodPtr a = &MyClass::Method; // legal MethodPtr b = &Method; // error C2276: ‘&’ : illegal operation on bound member function expression if (a == b) // this method has not been overridden? throw “Not overridden”; } };
ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function. This takes care of name mangling. So what you are trying to do will not work in a standards compliant C++ compiler.
1,802,185
1,802,205
Common Practice for Template Function Defination - Mix with Function Declaration?
Most of the time, I "avoid" to have the following style in my single header file. class a { void fun(); }; void a::fun() { } In order to avoid the following error. I try to separate class definition in cpp file and class declaration in h file. For example, the below is the wrong example : main.cpp #include "b.h" #include "a.h" int main() { a aa; b bb; } a.h #ifndef A_H #define A_H #include <iostream> class a { public: virtual int fun(); }; int a::fun() { int t; std::cout << "a" << std::endl; return t; } #endif b.h #ifndef B_H #define B_H #include <iostream> #include "a.h" class b { public: b(); }; #endif b.cpp #include "b.h" #include "a.h" b::b() { a aa; aa.fun(); } I will get the following error : 1>b.obj : error LNK2005: "public: virtual int __thiscall a::fun(void)" (?fun@a@@UAEHXZ) already defined in main.obj However, when come to template, I will usually do it this way : a.h #ifndef A_H #define A_H #include <iostream> template <typename T> class a { public: virtual T fun(); }; template<typename T> T a<T>::fun() { T t; std::cout << "a" << std::endl; return t; } #endif May I know it this a good practice? Thanks. Cheok
You can eliminate the LNK2005 error by declaring the definition of a::fun() as inline. For example: // a.h // ... inline int a::fun() { int t; std::cout << "a" << std::endl; return t; } With templates, the problem doesn't occur because the compiler/linker take care of ensuring that there is only one definition of each template instantiation. If, for some reason, you don't want the function to be inline, then you'll have to ensure that it only gets compiled once. For example, something like this: // a.h // ... #ifdef DEFINE_CLASS_A_FUNCTIONS int a::fun() { int t; std::cout << "a" << std::endl; return t; } #endif and then, somewhere, you'll need to do something like this (exactly once): #define DEFINE_CLASS_A_FUNCTIONS #include "a.h"
1,802,342
1,802,986
Please show me a situtation which shows `need` for Delegates (or) function pointers
I'm going take a class on "Delegates and Callbacks" to students who are learning level programmers. They have basic c/c++ & c# background. Instead of directly showing how to use them. I want to show "Why Function Pointers?" first. I want to start with an example situation and ask them "How will you do this"? and make them realize the need for something and then introduce them to FunctionPointers, Delegates & CallBacks. So, Can any one show me a good example which shows the need for Delegates in C# (or) function pointers in C/C++. I don't want example of event handling in GUI example and I don't want demonstration of "How to use delegates" with an examples of kind add2numbers etc.. I'm looking for something practical example where they could feel the need of FunctionPointers, Delegates & CallBacks. If there are any good articles, please post them.
You can show them an example of filtering a list of items in several places in your software. For example, you might have public List<Person> GetMale(List<Person> people) { List<Person> results = new List<Person>(); foreach (Person p in people) { if (p.IsMale) results.Add(p); } return results; } or public List<Person> GetFemale(List<Person> people) { List<Person> results = new List<Person>(); foreach (Person p in people) { if (!p.IsMale) results.Add(p); } return results; } To avoid repeating the foreach iteration in every method, you will want to extract the actual condition (i.e. a predicate in this case), and have it implemented somewhere else. So you will replace these two methods with: public List<Person> Filter(List<Person> people, Func<bool, Person> match) { List<Person> results = new List<Person>(); foreach (Person p in people) { if (match(p)) results.Add(p); } return results; } and then call it in your code like this: List<Person> malePersons = Filter(people, p => p.IsMale); List<Person> femalePersons = Filter(people, p => !p.IsMale); Note that the actual condition is now extracted outside of the iterating block, and you can reuse the same method to create any custom filtering logic you like. By extracting this logic, you are delegating the problem to someone else, making your code loosely coupled. Using C# 2.0 anonymous method syntax, calling this method would look like this: List<Person> malePersons = Filter(people, delegate (Person p) { return p.IsMale; }); List<Person> femalePersons = Filter(people, delegate (Person p) { return !p.IsMale; }); or using actual methods: List<Person> malePersons = Filter(people, MaleMatch); List<Person> femalePersons = Filter(people, FemaleMatch); where predicates are defined as: private bool MaleMatch(Person p) { return p.IsMale; } private bool FemaleMatch(Person p) { return !p.IsMale; } It is important to note that we are not passing the result of these methods, but actual method "pointers", so actual results will be returned when the method is called inside the Filter method. Note also that LINQ in .Net 3.5 already contains a Where extension method which does the same thing like this example, and many other methods which use delegates for conditions, projecting and other stuff, so you basically only need to pass a delegate with the appropriate signature.
1,802,418
1,802,602
Race between virtual function and pthread_create
When I try to create a class instance with a virtual method and pass it to pthread_create, I get a race condition, causing the caller to sometimes call the base method instead of the derived method like it should. After googling pthread vtable race, I found out this is fairly well-known behavior. My question is, what's a good way to get around it? The code below exhibits this behavior at any optimization setting. Note that the MyThread object is completely constructed before being passed to pthread_create. #include <errno.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> struct Thread { pthread_t thread; void start() { int s = pthread_create(&thread, NULL, callback, this); if (s) { fprintf(stderr, "pthread_create: %s\n", strerror(errno)); exit(EXIT_FAILURE); } } static void *callback(void *ctx) { Thread *thread = static_cast<Thread*> (ctx); thread->routine(); return NULL; } ~Thread() { pthread_join(thread, NULL); } virtual void routine() { puts("Base"); } }; struct MyThread : public Thread { virtual void routine() { } }; int main() { const int count = 20; int loop = 1000; while (loop--) { MyThread *thread[count]; int i; for (i=0; i<count; i++) { thread[i] = new MyThread; thread[i]->start(); } for (i=0; i<count; i++) delete thread[i]; } return 0; }
The only problem here is that you are deleting the objects before the spawned thread executes the method, so by that time the child destructor already fired and the object is not there anymore. So it has nothing to do with pthread_create or whatever, its your timing, you can't spawn a thread, give it some resources and delete them before he has the chance of using them. Try this, it'll show how the objs are destructed by main thread before spawned thread uses them: struct Thread { pthread_t thread; bool deleted; void start() { deleted=false; int s = pthread_create(&thread, NULL, callback, this); if (s) { fprintf(stderr, "pthread_create: %s\n", strerror(errno)); exit(EXIT_FAILURE); } } static void *callback(void *ctx) { Thread *thread = static_cast<Thread*> (ctx); thread->routine(); return NULL; } ~Thread() { pthread_join(thread, NULL); } virtual void routine() { if(deleted){ puts("My child deleted me"); } puts("Base"); } }; struct MyThread : public Thread { virtual void routine() { } ~MyThread(){ deleted=true; } }; In the other hand if you just place a sleep in main before deleting them you'll never have that problem because the spawned thread is using valid resources. int main() { const int count = 20; int loop = 1000; while (loop--) { MyThread *thread[count]; int i; for (i=0; i<count; i++) { thread[i] = new MyThread; thread[i]->start(); } sleep(1); for (i=0; i<count; i++) delete thread[i]; } return 0; }
1,802,471
1,802,501
Suppress console when calling "system" in C++
I'm using the system command in C++ to call some external program, and whenever I use it, a console window opens and closes after the command finishes. How can I avoid the opening of a console window? I would be happy if the solution could be platform-independent. I would also like for my program to wait until the command is finished.
It sounds like you're using windows. On Linux (and *nix in general), I'd replace the call to system with calls to fork and exec, respectively. On windows, I think there is some kind of spawn-a-new-process function in the Windows API—consult the documentation. When you're running shell commands and/or external programs, your program is hard to make platform-independent, as it will depend on the platform having the commands and/or external programs you're running.
1,802,528
1,816,724
Netbeans re produce Makefile when change options in c/c++ developing
I create new c/c++ project in Netbeans and change Makefile and add -lpthread for work with pthread and run my project .also I need to add some runtime argument from project properties/Run/Arguments . when I change runtime Arguments Makefiles that place at /'project folder'/nbproject/private/Makefile-Debug.mk & Makefile-Release.mk are re produced and my edit and -lpthread clear . now it's a bug ? or feature ? and how to avoid it ?
It is not feature, :( Makefiles are generated automatically so any your changes will be lost every time Makefile change (eg when you add new files to project) Solution is to use Netbean's Makefile Wizard! project properties->Linker->Libraries->Add Standard Library->Posix Threads or Add Option->Other Option-> -lpthread And Netbean will take care about Makefiles itself. EDIT (in response to first comment below): Alternative to Netbeans makefile wizards (and project properties) is to not use it! There are some good tools that have the same functionality as Netbeans Makefiles and all of them are based on Make. Look for Ant or qmake. But in that approach you will have to write configs for your app yourself (but written once require changes only if new files are added to project) and second disadvantage is that every time you wont to compile and run your app you will have to type a command in console.
1,802,556
1,802,578
#define TheVLM(x) VLM::Global()->x TheVLM(Run());
What does this mean in C++: #define TheVLM(x) VLM::Global()->x TheVLM(Run());
Are you sure it's not on two lines, like : #define TheVLM(x) VLM::Global()->x TheVLM(Run()); In that case, it's nothing specfic to C++, it is a standard use of Macro. The second line will generate the following call after macro substitution: VLM::Global()->Run();
1,802,899
1,802,916
Supporting multiple human languages
I am thinking about my final year project and the possibility of supporting multiple languages, e.g. English, Welsh, German etc.. Is there a standard way of supporting multiple human languages in a program? What is the recommended file format for storing the different languages? It is something I am clueless on but is obviously a very common feature, So any advice is welcomed. I am most familiar with c++ using mfc for UI applications, currently learning Qt. So an answer with this bias in mind would be good. (Sorry if this has been covered before, but searching for 'Languages' on SO returns streams of programming language related questions)
If you wanted to browse on StackOverflow for ideas you could try the internationalization, i18n, localization and l10n tags. ("i18n" == "internationalisation" because "nternationalizatio" is 18 letters. Same for localization and l10n.)