question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
2,885,535
2,885,617
Custom URL protocol in Windows to serve HTML content
This question addresses how to register a custom URL protocol to launch an application in response to a link, but I want my handler to serve dynamic content. Essentially, I'm looking to create a web application that runs on the user's machine instead of a web server. I could set up a localhost, but I want to use a "friendly" URL format that the user can reference elsewhere, e.g. a hypothetical cats protocol: cats:fluffy/cheeseburger-consumption-stats How can I accomplish this? Also, do you see any pitfalls with this approach, such as security warnings from browsers?
I did something similar a few years back, we had a local application and wrote a custom url handler so that we could embed these special links on our web page that when clicked would launch our application and load the file. The technology is called Asynchronous Pluggable Protocols - http://msdn.microsoft.com/en-us/library/aa767916(v=VS.85).aspx Here is a quick example explaining the registry settings you need to make and a sample app that handles requests - http://msdn.microsoft.com/en-us/library/aa767914(VS.85).aspx
2,885,597
2,886,432
C++ template name pretty print
I have need to print indented template names for debugging purposes. For example, instead of single-line, I would like to indent name like this: boost::phoenix::actor< boost::phoenix::composite< boost::phoenix::less_eval, boost::fusion::vector< boost::phoenix::argument<0>, boost::phoenix::argument<1>, I started writing my own but is getting to be complicated. Is there an existing solution? if there is not one, can you help me to finish up my implementation? I will post it if so. Thanks this is what typeid.name looks like, boost::phoenix::actor<boost::phoenix::composite<boost::phoenix::less_eval, boost::fusion::vector<boost::phoenix::argument<0>, boost::phoenix::composite<boost::phoenix::multiplies_eval, boost::fusion::vector<boost::phoenix::argument<1>, boost::phoenix::argument<2>, boost::fusion::void_, boost::fusion::void_, boost::fusion::void_, boost::fusion::void_, boost::fusion::void_, boost::fusion::void_, boost::fusion::void_, boost::fusion::void >, boost::fusion::void_, boost::fusion::void_, boost::fusion::void_, boost::fusion::void_, boost::fusion::void_, boost::fusion::void_, boost::fusion::void_, boost::fusion::void_> > > this is my goal 6 boost::phoenix::actor< 7 boost::phoenix::composite< 8 boost::phoenix::less_eval, 9 boost::fusion::vector< 10 boost::phoenix::argument<0>, 11 boost::phoenix::composite< 12 boost::phoenix::multiplies_eval, 13 boost::fusion::vector< 14 boost::phoenix::argument<1>, 15 boost::phoenix::argument<2>, 16 boost::fusion::void_, 17 boost::fusion::void_, 18 boost::fusion::void_, 19 boost::fusion::void_, 20 boost::fusion::void_, 21 boost::fusion::void_, 22 boost::fusion::void_, 23 boost::fusion::void >, // indentation messed up 24 boost::fusion::void_, 25 boost::fusion::void_, 26 boost::fusion::void_, 27 boost::fusion::void_, 28 boost::fusion::void_, 29 boost::fusion::void_, 30 boost::fusion::void_, 31 boost::fusion::void_ 32 > 33 > 34 > so that I can actually read declaration
Certainly not the most elegant piece, but this should get you going regarding the closing tags: std::string indent(std::string str, const std::string &indent = " ") { std::string indent_ = std::string("\n"); size_t token = 0; while ((token = str.find_first_of("<>,", token)) != std::string::npos) { switch(str[token]) { case '<': indent_.append(indent); case ',': str.insert(token + 1, indent_); break; case '>': indent_.erase(indent_.size() - indent.size()); str.insert(token, indent_); } token += indent_.size() + 1; const size_t nw = str.find_first_not_of(" ", token); if(nw != std::string::npos) { str.erase(token, nw-token); } } return str; }
2,885,750
2,885,827
Difficulties getting GraphViz working as a library in C++
Am working on a program that will allow a graph of nodes to be displayed and then updated visually as the nodes themselves are updated. I am fairly new to Visual Studio 2010 and am following the GraphViz guide located at on the GraphViz website in order to get GraphViz working as a library. I have the following code which is taken straight from the pdf linked above. #include <graphviz\gvc.h> #include <graphviz\cdt.h> #include <graphviz\graph.h> #include <graphviz\pathplan.h> using namespace std; int main(int argc, char **argv) { Agraph_t *g; Agnode_t *n, *m; Agedge_t *e; Agsym_t *a; GVC_t *gvc; /* set up a graphviz context */ gvc = gvContext(); /* parse command line args - minimally argv[0] sets layout engine */ gvParseArgs(gvc, argc, argv); /* Create a simple digraph */ g = agopen("g", AGDIGRAPH); n = agnode(g, "n"); m = agnode(g, "m"); e = agedge(g, n, m); /* Set an attribute - in this case one that affects the visible rendering */ agsafeset(n, "color", "red", ""); /* Compute a layout using layout engine from command line args */ gvLayoutJobs(gvc, g); /* Write the graph according to -T and -o options */ gvRenderJobs(gvc, g); /* Free layout data */ gvFreeLayout(gvc, g); /* Free graph structures */ agclose(g); /* close output file, free context, and return number of errors */ return (gvFreeContext(gvc)); } After compiling I get the following errors which indicate that I do not have it correctly linked. 1>main.obj : error LNK2019: unresolved external symbol _gvFreeContext referenced in function _main 1>main.obj : error LNK2019: unresolved external symbol _agclose referenced in function _main 1>main.obj : error LNK2019: unresolved external symbol _gvFreeLayout referenced in function _main 1>main.obj : error LNK2019: unresolved external symbol _gvRenderJobs referenced in function _main 1>main.obj : error LNK2019: unresolved external symbol _gvLayoutJobs referenced in function _main 1>main.obj : error LNK2019: unresolved external symbol _agsafeset referenced in function _main 1>main.obj : error LNK2019: unresolved external symbol _agedge referenced in function _main 1>main.obj : error LNK2019: unresolved external symbol _agnode referenced in function _main 1>main.obj : error LNK2019: unresolved external symbol _agopen referenced in function _main 1>main.obj : error LNK2019: unresolved external symbol _gvParseArgs referenced in function _main 1>main.obj : error LNK2019: unresolved external symbol _gvContext referenced in function _main Within the VC++ Directories I have C:\Program Files (x86)\Graphviz2.26.3\include in the Include Directories and C:\Program Files (x86)\Graphviz2.26.3\lib\release\lib in the Library Directories Any help would be greatly appreciated to help get this working. Thank you.
You normally need to add the .lib file to the additional input in the first section of the linking area. Correction: properties->Linker->Input->Additional Dependencies.
2,885,809
2,885,913
Where is a good place for a code review?
A few colleagues and I created a simple packet capturing application based on libpcap, GTK+ and sqlite as a project for a Networks Engineering course at our university. While it (mostly) works, I am trying to improve my programming skills and would appreciate it if members of the community could look at what we've put together. Is this a good place to ask for such a review? If not, what are good sites I can throw this question up on? The source code is hosted by Google Code (http://code.google.com/p/nbfm-sniffer) and an executable is available for download (Windows only, though it does compile on Linux and should compile on OS X Leopard as well provided one has gtk+ SDK installed). Thanks, everyone! -Carlos Nunez UPDATE: Thanks for the great feedback, everyone. The code is completely open-source and modifiable (licensed under Apache License 2.0). I was hoping to get more holistic feedback, considering that my postings would still be very lengthy.
You might get some mileage by posting the code out in the public space (through github or some other open-posting forum), putting a link here on SO, and seeing what happens. You could also make it an open-source project, and see if people find it and use it. Probably your best bet is to talk to your prof/classmates, find some professional programmers willing to devote their time, and have them review the code. Like American Idol-esque judging, but for your software...
2,885,822
2,886,422
Which logging library to use for cross-language (Java, C++, Python) system
I have a system where a central Java controller launches analysis processes, which may be written in C++, Java, or Python (mostly they are C++). All these processes currently run on the same server. What are you suggestions to Create a central log to which all processes can write to What if in the future I push some processes to another server. How can I support distributed logging? Thanks!
Apache has cross-platform logging libraries, which allow you to log from various programming languages using similar APIs. Unfortunately they don't have a Python API, though you should be able to whip one up with log4cpp and Boost.Python. A project I work on uses one of these libraries to log to a database, which allows us "distributed logging" with a centralized place for the log messages. I have to admit I'm not a fan of this. Another project I work on uses one of these libraries to log to the native logging facility. The Windows Event Log has some features for distributed logging, but AFAIK syslog does not. Although I don't have any experience with it, a better fit may be Facebook's Scribe project. The feature set meets your requirements, including a Python API. Unfortunately it uses Thrift which doesn't work for C++ on Windows (that is, the Thrift compiler generates C++ code that only works on UNIX). You may be able to get around this problem using Cygwin, but I can't promise that approach will work.
2,885,991
2,886,095
Extracting bool from istream in a templated function
I'm converting my fields class read functions into one template function. I have field classes for int, unsigned int, long, and unsigned long. These all use the same method for extracting a value from an istringstream (only the types change): template <typename Value_Type> Value_Type Extract_Value(const std::string& input_string) { std::istringstream m_string_stream; m_string_stream.str(input_string); m_string_stream.clear(); m_string_stream >> value; return; } The tricky part is with the bool (Boolean) type. There are many textual representations for Boolean: 0, 1, T, F, TRUE, FALSE, and all the case insensitive combinations Here's the questions: What does the C++ standard say are valid data to extract a bool, using the stream extraction operator? Since Boolean can be represented by text, does this involve locales? Is this platform dependent? I would like to simplify my code by not writing my own handler for bool input. I am using MS Visual Studio 2008 (version 9), C++, and Windows XP and Vista.
The strings for true and false are defined by std::numpunct::truename() and std::numpunct::falsename(). You can get the numpunct for a given stream with use_facet <numpunct <char> >(stream.getloc()), if I understand the documentation correctly. EDIT: You can toggle whether to use "1"/"0" or "true"/"false with std::noboolalpha and std::boolalpha.
2,886,146
2,886,207
Real-time spectrum analyzer with API
I'm looking for a C or C++ API that will give me real-time spectrum analysis of a waveform on Windows. I'm not entirely sure how large a sample window it should need to determine frequency content, but the smaller the better. For example, if it can work with a 0.5 second long sample and determine frequency content to the Hz, that would be wicked-awesome.
I used FFTW a few years ago. It is supposedly fast (though I didn't use it for anything real-time myself) and was certainly pretty easy to use, even on Windows. Regarding the window size, see the Nyquist-Shannon sampling theorem. (I imagine there are other issues involved when using a window on the data, particularly for low frequencies, but I'm no expert and I couldn't find any useful-looking info about this, so maybe I'm wrong.)
2,886,193
2,886,229
Visitor and templated virtual methods
In a typical implementation of the Visitor pattern, the class must account for all variations (descendants) of the base class. There are many instances where the same method content in the visitor is applied to the different methods. A templated virtual method would be ideal in this case, but for now, this is not allowed. So, can templated methods be used to resolve virtual methods of the parent class? Given (the foundation): struct Visitor_Base; // Forward declaration. struct Base { virtual accept_visitor(Visitor_Base& visitor) = 0; }; // More forward declarations struct Base_Int; struct Base_Long; struct Base_Short; struct Base_UInt; struct Base_ULong; struct Base_UShort; struct Visitor_Base { virtual void operator()(Base_Int& b) = 0; virtual void operator()(Base_Long& b) = 0; virtual void operator()(Base_Short& b) = 0; virtual void operator()(Base_UInt& b) = 0; virtual void operator()(Base_ULong& b) = 0; virtual void operator()(Base_UShort& b) = 0; }; struct Base_Int : public Base { void accept_visitor(Visitor_Base& visitor) { visitor(*this); } }; struct Base_Long : public Base { void accept_visitor(Visitor_Base& visitor) { visitor(*this); } }; struct Base_Short : public Base { void accept_visitor(Visitor_Base& visitor) { visitor(*this); } }; struct Base_UInt : public Base { void accept_visitor(Visitor_Base& visitor) { visitor(*this); } }; struct Base_ULong : public Base { void accept_visitor(Visitor_Base& visitor) { visitor(*this); } }; struct Base_UShort : public Base { void accept_visitor(Visitor_Base& visitor) { visitor(*this); } }; Now that the foundation is laid, here is where the kicker comes in (templated methods): struct Visitor_Cout : public Visitor_Base { template <class Receiver> void operator() (Receiver& r) { std::cout << "Visitor_Cout method not implemented.\n"; } }; Intentionally, Visitor_Cout does not contain the keyword virtual in the method declaration. All the other attributes of the method signatures match the parent declaration (or perhaps specification). In the big picture, this design allows developers to implement common visitation functionality that differs only by the type of the target object (the object receiving the visit). The implementation above is my suggestion for alerts when the derived visitor implementation hasn't implement an optional method. Is this legal by the C++ specification? (I don't trust when some says that it works with compiler XXX. This is a question against the general language.)
oh, I see what you're after. Try something like this: template < typename Impl > struct Funky_Visitor_Base : Visitor_Base { // err... virtual void operator()(Base_Int& b) { Impl::apply(b) } virtual void operator()(Base_Long& b) { Impl::apply(b) } virtual void operator()(Base_Short& b) { Impl::apply(b) } virtual void operator()(Base_UInt& b) { Impl::apply(b) } virtual void operator()(Base_ULong& b) { Impl::apply(b) } // this actually needs to be like so: virtual void operator()(Base_UShort& b) { static_cast<impl *const>(this)->apply(b) } }; struct weird_visitor : Funky_Visitor_Base<weird_visitor> { // Omit this if you want the compiler to throw a fit instead of runtime error. template < typename T > void apply(T & t) { std::cout << "not implemented."; } void apply(Base_UInt & b) { std::cout << "Look what I can do!"; } }; That said, you should look into the acyclic visitor pattern. It has misunderstood visitors built into the framework so you don't have to implement functions for stuff you'll never call. Funny thing is that I actually used something very similar to this to build an acyclic visitor for a list of types. I applied a metafunction that basically builds Funky_Visitor_Base and turns an operator (something with an apply() like I show) into a visitor for that complete list. The objects are reflective so the apply() itself is actually a metafunction that builds based on whatever type it's hitting. Pretty cool and weird actually.
2,886,259
2,886,675
gcc 4.5 installation problem under ubuntu
I tried to install gcc 4.5 on ubuntu 10.04 but failed. Here is a compile error that I don't know how to solve. Is there anyone successfully install the latest gcc on ubuntu? Following is my steps and the error message, I'd like to know where is the problem.... Step1: download these files: gcc-core-4.5.0.tar.gz gcc-g++-4.5.0.tar.gz gmp-4.3.2.tar.bz2 mpc-0.8.1.tar.gz mpfr-2.4.2.tar.gz Step2: Unzip above files Step3: move gmp, mpc, mpfr to the gcc-4.5.0/ directory. mv gmp-4.3.2 gcc-4.5.0/gmp mv mpc-0.8.1 gcc-4.5.0/mpc mv mpfr-2.4.2 gcc-4.5.0/mpfr Step4: go to gcc-4.5.0 directory and do configuration: sudo ./configure Step5: compile and install sudo make sudo make install The first 4 steps is OK, I can configure it successfully. However, when I try to compile it, following error message comes out, I cannot figure out what the problem is. Should I change the name from "gcc 4.5" to "gcc"?? It's a little strange that we need to do this by ourself. Is there anything I missed during the installation? xxx@xxx-laptop:/media/Data/Tool/linux/gcc 4.5/gcc-4.5.0$ sudo make [sudo] password for xxx: [ -f stage_final ] || echo stage3 > stage_final /bin/bash: line 2: test: /media/Data/Tool/linux/gcc: binary operator expected /bin/bash: /media/Data/Tool/linux/gcc: No such file or directory make[1]: Entering directory `/media/Data/Tool/linux/gcc 4.5/gcc-4.5.0' make[2]: Entering directory `/media/Data/Tool/linux/gcc 4.5/gcc-4.5.0' make[3]: Entering directory `/media/Data/Tool/linux/gcc 4.5/gcc-4.5.0' rm -f stage_current make[3]: Leaving directory `/media/Data/Tool/linux/gcc 4.5/gcc-4.5.0' make[2]: Leaving directory `/media/Data/Tool/linux/gcc 4.5/gcc-4.5.0' make[2]: Entering directory `/media/Data/Tool/linux/gcc 4.5/gcc-4.5.0' Configuring stage 1 in host-x86_64-unknown-linux-gnu/intl /bin/bash: /media/Data/Tool/linux/gcc: No such file or directory make[2]: *** [configure-stage1-intl] Error 127 make[2]: Leaving directory `/media/Data/Tool/linux/gcc 4.5/gcc-4.5.0' make[1]: *** [stage1-bubble] Error 2 make[1]: Leaving directory `/media/Data/Tool/linux/gcc 4.5/gcc-4.5.0' make: *** [all] Error 2
It might not be a good idea to have a space in your path - it's kind of rare and can easily mess up shell scripts that aren't specially designed to deal with it (which is a bad combination!) Another potential problem is that you're running configure inside the gcc source directory - this isn't recommended (and didn't work at all for me on at least one version of gcc 4). Instead make an empty build directory, parallel to the source directory, so you have something like: gcc 4.5 <- but might want to avoid the space gcc-4.5.0 ... build Then cd into build and run ../gcc-4.5.0/configure You may also need to start from a freshly unzipped source directory, as the previous failed build may have broken it.
2,886,306
2,886,319
C++ header files and variable scope
I want to organize my c++ variables and functions in the following way: function prototypes in a header file "stuff.h", function implementation in "stuff.cpp", then say #include "stuff.h" in main.cpp (so I can call functions implemented in stuff.cpp). So far so good. Now I want to declare some variables in stuff.cpp that have global scope (so I can modify the variables in functions implemented in stuff.cpp and main.cpp). This doesn't seem to work. How can I do this?
Declare them as extern. E.g., in stuff.h: extern int g_number; Then in stuff.cc: int g_number = 123; Then in main.cc just #include stuff.h.
2,886,393
2,886,779
Creating rapid function overloads in C++
template<typename Functor, typename Return, typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7, typename Arg8, typename Arg9, typename Arg10> class LambdaCall : public Instruction { public: LambdaCall(Functor func ,unsigned char constructorarg1 ,unsigned char constructorarg2 ,unsigned char constructorarg3 ,unsigned char constructorarg4 ,unsigned char constructorarg5 ,unsigned char constructorarg6 ,unsigned char constructorarg7 ,unsigned char constructorarg8 ,unsigned char constructorarg9 ,unsigned char constructorarg10) : arg1(constructorarg1) , arg2(constructorarg2) , arg3(constructorarg3) , arg4(constructorarg4) , arg5(constructorarg5) , arg6(constructorarg6) , arg7(constructorarg7) , arg8(constructorarg8) , arg9(constructorarg9) , arg10(constructorarg10) , function(func) {} void Call(State& state) { state.Push<Return>(func(*state.GetRegisterValue<Arg1>(arg1) ,*state.GetRegisterValue<Arg1>(arg1) ,*state.GetRegisterValue<Arg2>(arg2) ,*state.GetRegisterValue<Arg3>(arg3) ,*state.GetRegisterValue<Arg4>(arg4) ,*state.GetRegisterValue<Arg5>(arg5) ,*state.GetRegisterValue<Arg6>(arg6) ,*state.GetRegisterValue<Arg7>(arg7) ,*state.GetRegisterValue<Arg8>(arg8) ,*state.GetRegisterValue<Arg9>(arg9) ,*state.GetRegisterValue<Arg10>(arg10) )); } Functor function; unsigned char arg1; unsigned char arg2; unsigned char arg3; unsigned char arg4; unsigned char arg5; unsigned char arg6; unsigned char arg7; unsigned char arg8; unsigned char arg9; unsigned char arg10; }; Then again for every possible number of arguments I want to support, and again for void returns. Any way to do this faster? Edit: Apparently there's some (understandable) confusion about the goal of the above function. I want to create a function that accepts N template arguments, has N unsigned char variables, accepts them in it's constructor and assigns them, calls a specific function with the Nth template and Nth char arguments, and passes the return into a given lamba function, which then passes it's return into the last function, which has a special template argument. Then I want this to work for any given quantity of arguments or void returns. Preferably without writing an overload for every single argument number and void return possibility, since that would involve 22 specializations. Edit: Without variadics, not any given quantity, but up to say ten. I checked out the Boost preprocessor library, but it's not working.
Turns out I just suck at the boost preprocessing library. #define ternary(z, n, data) data BOOST_PP_COMMA_IF(BOOST_PP_NOT_EQUAL(n, BOOST_PP_SUB(WIDE_RECURSE_UPPER_LIMIT, WIDE_RECURSE))) #define argternary(z, n, data) data ## n BOOST_PP_COMMA_IF(BOOST_PP_LESS(n, BOOST_PP_SUB(WIDE_RECURSE, 1))) template<typename Functor, typename Return, BOOST_PP_REPEAT(WIDE_RECURSE, argternary, typename Arg) > class LambdaCall <Functor, Return BOOST_PP_COMMA() BOOST_PP_ENUM_PARAMS(WIDE_RECURSE, Arg) BOOST_PP_COMMA_IF(BOOST_PP_LESS(WIDE_RECURSE, BOOST_PP_SUB(WIDE_RECURSE_UPPER_LIMIT, 1))) BOOST_PP_REPEAT(BOOST_PP_SUB(WIDE_RECURSE_UPPER_LIMIT, WIDE_RECURSE), ternary, void) > : public Instruction { #undef ternary #undef argternary public: LambdaCall(Functor func, BOOST_PP_ENUM_PARAMS(WIDE_RECURSE, unsigned char constructorarg) ) #define TEMPDECL(n) arg ## n ( constructorarg ## n), #define DECL(z, n, text) TEMPDECL(n) : BOOST_PP_REPEAT(WIDE_RECURSE, DECL, hi) function(func) {} void Call(State& state) { state.Push<Return>( func( #undef DECL #define DECL(z, n, text) *state.GetRegisterValue<Arg ## n>(arg ## n) BOOST_PP_COMMA_IF(BOOST_PP_LESS(n, BOOST_PP_SUB(WIDE_RECURSE, 1))) BOOST_PP_REPEAT(WIDE_RECURSE, DECL, hi) )); } Functor function; #undef DECL #define DECL(z, n, text) text ## n; BOOST_PP_REPEAT(WIDE_RECURSE, DECL, unsigned char arg) }; #undef DECL #undef TEMPDECL #define ternary(z, n, data) data BOOST_PP_COMMA_IF(BOOST_PP_NOT_EQUAL(n, BOOST_PP_SUB(WIDE_RECURSE_UPPER_LIMIT, WIDE_RECURSE))) #define argternary(z, n, data) data ## n BOOST_PP_COMMA_IF(BOOST_PP_NOT_EQUAL(n, BOOST_PP_SUB(WIDE_RECURSE, 1))) template<typename Functor, BOOST_PP_REPEAT(WIDE_RECURSE, argternary, typename Arg) > class LambdaCall <Functor, void, BOOST_PP_ENUM_PARAMS(WIDE_RECURSE, Arg) BOOST_PP_COMMA_IF(BOOST_PP_LESS(WIDE_RECURSE, BOOST_PP_SUB(WIDE_RECURSE_UPPER_LIMIT, 1))) BOOST_PP_REPEAT(BOOST_PP_SUB(WIDE_RECURSE_UPPER_LIMIT, WIDE_RECURSE), ternary, void) > : public Instruction { #undef ternary #undef argternary public: LambdaCall(Functor func, BOOST_PP_ENUM_PARAMS(WIDE_RECURSE, unsigned char constructorarg) ) #define TEMPDECL(n) arg ## n ( constructorarg ## n), #define DECL(z, n, text) TEMPDECL(n) : BOOST_PP_REPEAT(WIDE_RECURSE, DECL, hi) function(func) {} void Call(State& state) { func( #undef DECL #define DECL(z, n, text) *state.GetRegisterValue<Arg ## n>(arg ## n) BOOST_PP_COMMA_IF(BOOST_PP_LESS(n, BOOST_PP_SUB(WIDE_RECURSE, 1))) BOOST_PP_REPEAT(WIDE_RECURSE, DECL, hi) ); } Functor function; #undef DECL #define DECL(z, n, text) text ## n; BOOST_PP_REPEAT(WIDE_RECURSE, DECL, unsigned char arg) }; #undef DECL #undef TEMPDECL #undef WIDE_RECURSE Using: #define WIDE_RECURSE_UPPER_LIMIT 10 #define WIDE_RECURSE 10 #include "functors.h" #define WIDE_RECURSE 9 #include "functors.h" #define WIDE_RECURSE 8 #include "functors.h" #define WIDE_RECURSE 7 #include "functors.h" #define WIDE_RECURSE 6 #include "functors.h" #define WIDE_RECURSE 5 #include "functors.h" #define WIDE_RECURSE 4 #include "functors.h" #define WIDE_RECURSE 3 #include "functors.h" #define WIDE_RECURSE 2 #include "functors.h" #define WIDE_RECURSE 1 #include "functors.h" Pretty much generated what I was looking for.
2,886,588
2,886,595
TrackMouseEvent not working
Basically, I call TrackMouseEvent in my WM_CREATE then I also called it again after a WM_MOUSELEAVE event, but this freezes up my program. Where should I be sticking it?
You need to call TrackMouseEvent when the mouse enters your control, and not when it leaves your control. You can call TrackMouseEvent on the WM_MOUSEMOVE message. You don't need to call TrackMouseEvent every time WM_MOUSEMOVE is fired, just once up until you get another WM_MOUSELEAVE. After you get a WM_MOUSELEAVE you can set some flag so the next call to WM_MOUSEMOVE will know to call TrackMouseEvent again. Basically you can emulate a fictional WM_MOUSEENTER by using WM_MOUSEMOVE and also having that flag set.
2,886,601
2,886,755
initializing a vector of custom class in c++
Hey basically Im trying to store a "solution" and create a vector of these. The problem I'm having is with initialization. Heres my class for reference class Solution { private: // boost::thread m_Thread; int itt_found; int dim; pfn_fitness f; double value; std::vector<double> x; public: Solution(size_t size, int funcNo) : itt_found(0), x(size, 0.0), value(0.0), dim(30), f(Eval_Functions[funcNo]) { for (int i = 1; i < (int) size; i++) { x[i] = ((double)rand()/((double)RAND_MAX))*maxs[funcNo]; } } Solution() : itt_found(0), x(31, 0.0), value(0.0), dim(30), f(Eval_Functions[1]) { for (int i = 1; i < 31; i++) { x[i] = ((double)rand()/((double)RAND_MAX))*maxs[1]; } } Solution operator= (Solution S) { x = S.GetX(); itt_found = S.GetIttFound(); dim = S.GetDim(); f = S.GetFunc(); value = S.GetValue(); return *this; } void start() { value = f (dim, x); } /* plus additional getter/setter methods*/ } Solution S(30, 1) or Solution(2, 5) work and initalizes everything, but I need X of these solution objects. std::vector<Solution> Parents(X) will create X solutions with the default constructor and i want to construct using the (int, int) constructor. Is there any easy(one liner?) way to do this? Or would i have to do something like: size_t numparents = 10; vector<Solution> Parents; Parents.reserve(numparents); for (int i = 0; i<(int)numparents; i++) { Solution S(31, 0); Parents.push_back(S); }
the example I gave as a comment uses copy constructor to create new objects. You can do the following: // override copy constructor Solution(const Solution &solution) { ... copy from another solution } however be careful, as you no longer going to have exact object copy/construct if you introduce random generation in your copy constructor, i.e. Solution y = x; y != x your best solution is something like you already have in my opinion
2,886,609
2,886,654
How to make multiple windows using Win32 API
I see plenty of tutorials and articles showing me how to make a simple windows program, which is great but none of them show me how to make multiple windows. Right now I have working code that creates and draws a layered window and I can blit stuff using GDI to draw anything I want on it, drag it around, even make it transparent, etc. But I wanted a second rectangular area that I can draw to, drag around, etc. In other words, a second window. Probably want it to be a child window. Question is, how do I make it? Also, if anybody knows any good resources (online preferably) like articles or tutorials for window management in the Windows API, please share.
You can hit CreateWindow() more than once if you want. The message loop in your WinMain will pass events to all the windows that WinMain creates. You can even create two overlapped windows and set the parent window of the 2nd one to be the handle of the 1st one if you want.
2,886,671
2,886,695
Should I use a global var or call the function every time? C++
Im using: bool GetOS(LPTSTR pszOS) { OSVERSIONINFOEX osve; BOOL bOsVersionInfoEx; ZeroMemory(&osve, sizeof(OSVERSIONINFOEX)); osve.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); if( !(bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osve)) ) return false; TCHAR buf[80]; StringCchPrintf( buf, 80, TEXT("%u.%u.%u.%u"), osve.dwPlatformId, osve.dwMajorVersion, osve.dwMinorVersion, osve.dwBuildNumber); StringCchCat(pszOS, BUFSIZE, buf); return true; } to get the windows version, and I am planning to use pszOS every a few minutes, Should I use pszOS as a global var or call GetOS() every time? What's the best option from a performance point of view.
What's the best option from a performance point of view. Using a variable is much more efficient than a function call even if the function is empty. Just make sure that you initialize this variable when you have a single thread and then don't change it. Does it really matter though? From the info provided it's hard to tell, but is it really important that this runs extremely fast? Do you use it very very very often? It's safer to do the function call especially in a multi threaded environment. Don't optimize prematurely if you aren't sure this is a bottleneck in your program. Code in the safest way possible.
2,886,800
2,886,818
C++ Why am I unable to use an enum declared globally outside of the class it was declared in?
Right now, my project has two classes and a main. Since the two classes inherit from each other, they are both using forward declarations. In the first object, right underneath the #include statement, I initialize two enums, before the class definition. I can use both enums just fine inside that class. However, if I try to use those enums in the other class, which inherits from the first one, I get an error saying the enum has not been declared. If I try to redefine the enum in the second class, I get a redefinition error. I have even tried using a trick I just read about, and putting each enum in its own namespace; that didn't change anything. Here's an example: #ifndef CLASSONE_H #define CLASSONE_H namespace Player { enum Enum { One, Two, }; } #endif Then inside the second class, I attempt to use the enum declared earlier: void AddPlayer(Player::Enum playerNumber); and instead get an error saying 'Player' has not been declared.
I'm not sure what issue you are having without seeing your code, but this compiles: enum OutsideEnum { OE_1, OE_2, }; namespace ns { enum NSEnum { NE_1, NE_2, }; } class Base { public: enum BaseEnum { BE_1, BE_2, }; void BaseFunc(); }; class Derived { public: enum DerivedEnum { DE_1, DE_2, }; void DerivedFunc(); }; void Base::BaseFunc() { BaseEnum be = BE_1; Derived::DerivedEnum de = Derived::DE_1; OutsideEnum oe = OE_1; ns::NEEnum ne = ns::NE_1; } void Derived::DerivedFunc() { Base::BaseEnum be = Base::BE_1; DerivedEnum de = DE_1; OutsideEnum oe = OE_1; ns::NEEnum ne = ns::NE_1; } int main() { Base::BaseEnum be = Base::BE_1; Derived::DerivedEnum de = Derived::DE_1; OutsideEnum oe = OE_1; ns::NEEnum ne = ns::NE_1; } Two things to watch for with enums defined inside a class definition: Make sure it's declared public if you want it publicly available. When referencing it from anywhere other than the class it's defined in, use the class name to qualify the name of the enum and the values. EDIT: Ok, the problem has nothing to do with enums, but rather order of inclusion, when you have a base class and a derived class, only the derived class needs to know about the base class: Base class header: #ifndef BASE_H #define BASE_H enum BaseEnum { }; class Base { }; #endif Derived class header: #ifndef DERIVED_H #define DERIVED_H #include "Base.h" class Derived { void Func(BaseEnum be); }; #endif
2,886,831
2,901,465
Win32 C/C++ Load Image from memory buffer
I want to load an image (.bmp) file on a Win32 application, but I do not want to use the standard LoadBitmap/LoadImage from Windows API: I want it to load from a buffer that is already in memory. I can easily load a bitmap directly from a file and print it on the screen, but this issue is making me stuck. What I'm looking for is a function that works like this: HBITMAP LoadBitmapFromBuffer(char* buffer, int width, int height);
Nevermind, I found my solution! Here's the initializing code: std::ifstream is; is.open("Image.bmp", std::ios::binary); is.seekg (0, std::ios::end); length = is.tellg(); is.seekg (0, std::ios::beg); pBuffer = new char [length]; is.read (pBuffer,length); is.close(); tagBITMAPFILEHEADER bfh = *(tagBITMAPFILEHEADER*)pBuffer; tagBITMAPINFOHEADER bih = *(tagBITMAPINFOHEADER*)(pBuffer+sizeof(tagBITMAPFILEHEADER)); RGBQUAD rgb = *(RGBQUAD*)(pBuffer+sizeof(tagBITMAPFILEHEADER)+sizeof(tagBITMAPINFOHEADER)); BITMAPINFO bi; bi.bmiColors[0] = rgb; bi.bmiHeader = bih; char* pPixels = (pBuffer+bfh.bfOffBits); char* ppvBits; hBitmap = CreateDIBSection(NULL, &bi, DIB_RGB_COLORS, (void**) &ppvBits, NULL, 0); SetDIBits(NULL, hBitmap, 0, bih.biHeight, pPixels, &bi, DIB_RGB_COLORS); GetObject(hBitmap, sizeof(BITMAP), &cBitmap);
2,886,922
2,887,102
Casting to derived type problem in C++
I am quite new to C++, but have worked with C# for years, however it is not helping me here! :) My problem: I have an Actor class which Ball and Peg both derive from on an objective-c iphone game I am working on. As I am testing for collision, I wish to set an instance of Ball and Peg appropriately depending on the actual runtime type of actorA or actorB. My code that tests this as follows: // Actors that collided Actor *actorA = (Actor*) bodyA->GetUserData(); Actor *actorB = (Actor*) bodyB->GetUserData(); Ball* ball; Peg* peg; if (static_cast<Ball*> (actorA)) { // true ball = static_cast<Ball*> (actorA); } else if (static_cast<Ball*> (actorB)) { ball = static_cast<Ball*> (actorB); } if (static_cast<Peg*> (actorA)) { // also true?! peg = static_cast<Peg*> (actorA); } else if (static_cast<Peg*> (actorB)) { peg = static_cast<Peg*> (actorB); } if (peg != NULL) { [peg hitByBall]; } Once ball and peg are set, I then proceed to run the hitByBall method (objective c). Where my problem really lies is in the casting procedurel Ball casts fine from actorA; the first if (static_cast<>) statement steps in and sets the ball pointer appropriately. The second step is to assign the appropriate type to peg. I know peg should be a Peg type and I previously know it will be actorB, however at runtime, detecting the types, I was surprised to find actually the third if (static_cast<>) statement stepped in and set this, this if statement was to check if actorA was a Peg, which we already know actorA is a Ball! Why would it have stepped here and not in the fourth if statement? The only thing I can assume is how casting works differently from c# and that is it finds that actorA which is actually of type Ball derives from Actor and then it found when static_cast<Peg*> (actorA) is performed it found Peg derives from Actor too, so this is a valid test? This could all come down to how I have misunderstood the use of static_cast. How can I achieve what I need? :) I'm really uneasy about what feels to me like a long winded brute-casting attempt here with a ton of ridiculous if statements. I'm sure there is a more elegant way to achieve a simple cast to Peg and cast to Ball dependent on actual type held in actorA and actorB. Hope someone out there can help! :) Thanks a lot.
Since this is Objective-C code (not C++, as per the title), why not just call: [actorA hitByBall]; [actorB hitByBall]; Updated: If the object you are sending the message to is nil it will be ignored. If the object you send the message to does not implement hitByBall, you'll get an exception, "selector not recognized", unless you have put an empty definition in your base class (Actor). You can then remove your ball and peg declarations and all of the static_casts (which would have been incorrect even in C++).
2,886,984
2,887,031
inspect C++ template instantiation
Is there some utility which would allow me to inspect template instantiation? my compiler is g++ or Intel. Specific points I would like: Step by step instantiation. Instantiation backtrace (can hack this by crashing compiler. Better method?) Inspection of template parameters. @gf helpd me with simple type printing, C++ template name pretty print. However I am getting into boost phoenix and template level makes it very hard to understand what is going on and I would like intelligent solution also, if you have some techniques inspecting template instantiation, can you please share them. Thanks
With templates we simply don't have clean output facilities and there are no compilers i know of that allow you to directly view template instantiations. The closest i found regarding metaprogram debugging was a paper on Templight. For now the best utilities seem to be: static asserts & concept checks (clearly assert your assumptions) the mentioned instantiation backtraces (e.g. by using static asserts) letting instantiations generate warnings (boost::mpl::print might do it) a tracer, a custom class that gets passed as a template argument and is used to emit runtime output (introduced by C++ Templates - The Complete Guide)
2,887,047
2,887,081
Is there a C++ graphing library?
Is there a C++ graphing library that can display visual graphs (such as hyperbolas and parabolas and linear equations) based on the equation it is given and that is cross platform? Or am I just asking for too much...
Let's take your question step by step. "based on the equation [that] it is given" This would require you to write an expression parser; C++ cannot interpret equations "on the fly" without you writing a procedure to do so. For this, I recommend you look at Bison (go straight to the example RPN calc to get the idea). For the libraries, you can get any GUI toolkit for C++; there are dozens; the recommendation for QT is probably the most honest one. Check also Wikipedia. You need any toolkit which will provide you with a canvas where you can paint or render lines or splines. This is not trivial, but also not difficult. Your program would probably work as follows: Get a mathematical expression (or the parameters for a known function; like the axes and center of an ellipse). Generate a set of points (this is done with a loop in C++) Pack those points and sent them to the paint or render method of your toolkit (with the appropriate scaling/normalization Again, this is not trivial but not difficult either. You are reinventing the wheel, but I commend you for that. Cheers, J.
2,887,167
2,887,176
What could possibly cause this error when declaring an object inside a class?
I'm battling with this assignment :) I've got two classes: Ocean and Grid. When I declare an object of the Grid inside the Ocean: unsigned int sharkCount; Grid grid; The compiler/complainer says: error C2146: syntax error : missing ';' before identifier 'grid' Can you possibly predict what produces this error with the limited info I provided? It seems that as if the Ocean doesn't like the Grid class. Could this be because of the poor implementation of the grid class. BTW the Grid has a default constructor. Yet the error happens in compiling time!. EDIT: They're each in separate header file, and I've included the Grid.h in the Ocean.h.
My first guess would be that the definition of Grid simply isn't visible at the point that you've tried to use it in Ocean. Typically this happens if you have each in its own file, and haven't used a header to allow each to be "seen" by the other.
2,887,205
2,887,226
C++: looking for thread based a parallel kd tree library
Are there some implementation for KD-Tree on shared memory machines? thanks Arman.
libkdtree++ or kdtree
2,887,302
2,887,445
Lambda Expressions and Memory Management
How do the Lambda Expressions / Closures in C++0x complicate the memory management in C++? Why do some people say that closures have no place in languages with manual memory management? Is their claim valid and if yes, what are the reasons behind it?
Lambdas can outlive the context they were created in. Binding free variables by reference can be an issue then, because when the lambda wants to access them later, they may not exist anymore. It's simply "Don't return local variables by reference" in disguise.
2,887,465
2,887,555
C++ header and implementation files: what to include?
There is a .h file and a .cpp file with the same name but different extension. If I want to use what's in the .cpp file, do I include the .h file or the .cpp file?
The simple answer is that you almost always want to include .h files, and compile .cpp files. CPP files are (usually) the true code, and H files are (usually) forward-declarations. The longer answer is that you may be able to include either, and it might work for you, but both will give slightly different results. What "include" does is basically copy/paste the file in at that line. It doesn't matter what the extension is, it will include the contents of the file the same way. But C++ code is, by convention, usually written this way: SomeClass.cpp - #include "SomeClass.h" #include <iostream> void SomeClass::SomeFunction() { std::cout << "Hello world\n"; } SomeClass.h - class SomeClass { public: void SomeFunction(); }; If you include either of those, you can use the code from it. However, if you have multiple files that include the same .cpp file, you may get errors about re-definition. Header files (.h files) usually contain only forward declarations, and no implementations, so including them in multiple places won't give you errors about re-definition. If you somehow manage to compile without errors when including .cpp files from other .cpp files, you can still end up with duplicate code. This happens if you include the same .cpp files in multiple other files. It's like you wrote the function twice. This will make your program bigger on disk, take longer to compile, and run a bit slower. The main caveat is that this implementation/forward declaration convention doesn't hold true for code that uses templates. Template code will still be handed to you as .h files, but it (usually) is implemented directly in the .h file, and won't have accompanying .cpp files.
2,887,498
2,887,504
C++ man pages in Ubuntu
In Ubuntu linux I can't get any man pages for C++ keywords. Is there some kind of package I can install to fix this?
sudo apt-get install manpages-dev glibc-doc Look here too for STL.
2,887,507
2,887,517
What do I need to include in my header file for ostream
When I try to compile my program the compiler complains about this line in a .h file that I #included. ostream & Print (ostream & stream); How can this be fixed?
If you #include <ostream>, ostream will be defined in the std namespace: #include <ostream> // ... std::ostream & Print (std::ostream & stream);
2,887,583
2,887,595
Could a derived-class object treated as if it's the same type of a bases class? <noobieQ/>
Say I got: class X_ { public: void do() { } } class Y_ : public X_ { } And I have this function: void foo(X_ whatever) { whatever.do(); } Can I send a "Y_" object to the foo function, would this work? I just realized that I could have tested this myself :)
Yes, but it will get sliced - all the Y_ parts of the object will be chopped off, and it will become an X_. You normally need to pass by reference in this situation, as normally do() will be a virtual function: void foo(X_ & whatever) // ampersand means whatever is a reference { whatever.do(); } BTW, I don't know what you think those suffixed underscores are gaining you, but I would have said "nothing".
2,887,600
2,887,626
reverse a linked list?
Im trying to reverse the order of the following linked list, I've done so, But the reversed list does not seem to print out. Where have I gone wrong? //reverse the linked list #include <iostream> using namespace std; struct node{ int number; node *next; }; node *A; void addNode(node *&listpointer, int num){ node *temp; temp = new node; temp->number = num; temp->next = listpointer; listpointer = temp; } void reverseNode(node *&listpointer){ node *temp,*current; current = listpointer; temp = new node; while (true){ if (current == NULL){ temp = NULL; break; } temp->number = current->number; current = current->next; temp = temp->next; } listpointer = temp; } int main(){ A = NULL; addNode(A,1); addNode(A,2); addNode(A,3); while (true){ if (A == NULL){break;} cout<< A->number << endl; A = A->next; } cout<< "****" << endl; reverseNode(A); while (true){ if (A == NULL){break;} cout<< A->number << endl; A = A->next; } cout<< "****"<< endl; return 0; }
Well, the first thing I notice is that you are doing temp = new node and then, on every interaction: temp = temp->next but you are never assigning temp->next so when you finally override the list pointer you are surely giving back some funny value.
2,887,707
2,895,784
How to build Boost with C++0x support?
I don't know how to build Boost with C++0x compilers. Which option must be given to bjam? Should the user.config file be modified?Can someone help me? Best, Vicente
I have found the answer. I was waiting for a features something like 'std' and call it as follows: bjam std=0x but currently we need to use the low level variables cxxflags and add the specific compiler flags. For example for gcc we can do bjam toolset=gcc cxxflags=-std=gnu++0x Other compilers will need a different setting. Waiting for a new Boost.Build feature, you can also define your own toolset as follows: Add the user.config or site.config file using gcc : std0x : "/usr/bin/g++" # your path to the C++0x compiler : <cxxflags>-std=gnu++0x ; And now call as bjam toolset=gcc-std0x
2,887,713
2,890,419
C++ creating generic template function specialisations
I know how to specialise a template function, however what I want to do here is specialise a function for all types which have a given method, eg: template<typename T> void foo(){...} template<typename T, if_exists(T::bar)>void foo(){...}//always use this one if the method T::bar exists T::bar in my classes is static and has different return types. I tried doing this by having an empty base class ("class HasBar{};") for my classes to derive from and using boost::enable_if with boost::is_base_of on my "specialised" version. However the problem then is that for classes that do have bar, the compiler cant resolve which one to use :(. template<typename T> typename boost::enable_if<boost::is_base_of(HasBar, T>, void>::type f() {...} I know that I could use boost::disable_if on the "normal" version, however I do not control the normal version (its provided by a third party library and its expected for specialisations to be made, I just don't really want to make explicit specialisations for my 20 or so classes), nor do I have that much control over the code using these functions, just the classes implementing T::bar and the function that uses it. Is there some way to tell the compiler to "always use this version if possible no matter what" without altering the other versions? EDIT: I tried a different approach using a template class and explicit specialisations, but this is apparently also not allowed...Anyway to make this approach work? template<typename T>class ImpFoo { public: //error C3637: 'foo' : a friend function definition cannot be a specialization of a function template template<> friend void foo<T>(){...} }; ... class SomeClass : public ImpFoo<T> { ... SomeType bar(){...} };
Sadly you are out of luck in this situation as descriped, the best thing you can do is to explicitly specialize the templates as @aaa says. As you can limit these specializations to a simple forwarding to one central function, the overhead for 20 classes should be bearable. E.g.: template<class T> my_foo() { /* do the actual work */ } template<> void foo<MyClass01>() { my_foo<MyClass01>(); } // ... template<> void foo<MyClass20>() { my_foo<MyClass20>(); }
2,888,134
2,888,206
Rendering sub tools on vertical toolbar
I was wondering how ex Photoshop and Expression Design render sub tools. These show up when for example you hold your mouse down on the fill tool, a sub menu comes up to your right with the fill and gradient tools. I'm just not sure how to go about this because this sub menu would essentially have to be an extension of my toolbar, but then it would find itself on my Frame control. How is this handled? Would it be a good idea to just paint on my frame? Thanks
I'm pretty sure that they are created as bona fide transient windows much as the pop-up File menu and sub-menus are. I'd look at the source of GTK or similar to see how precisely that is done. Painting directly on the frame tends to make a window system unhappy.
2,888,501
2,888,514
Using a bitwise AND on more than two bits
I am pretty new to bitwise operators. Let's say I have 3 variables a, b and c, with these values in binary: a = 0001 b = 0011 c = 1011 Now, I want to perform a bitwise AND like this: a AND b AND c -------- d = 0001 d &= a &= b &= c doesn't work (as I expected), but how can I do this? Thanks
What's wrong with just this. d = a & b & c;
2,888,521
2,888,624
std::string manipulation: whitespace, "newline escapes '\'" and comments #
Kind of looking for affirmation here. I have some hand-written code, which I'm not shy to say I'm proud of, which reads a file, removes leading whitespace, processes newline escapes '\' and removes comments starting with #. It also removes all empty lines (also whitespace-only ones). Any thoughts/recommendations? I could probably replace some std::cout's with std::runtime_errors... but that's not a priority here :) const int RecipeReader::readRecipe() { ifstream is_recipe(s_buffer.c_str()); if (!is_recipe) cout << "unable to open file" << endl; while (getline(is_recipe, s_buffer)) { // whitespace+comment removeLeadingWhitespace(s_buffer); processComment(s_buffer); // newline escapes + append all subsequent lines with '\' processNewlineEscapes(s_buffer, is_recipe); // store the real text line if (!s_buffer.empty()) v_s_recipe.push_back(s_buffer); s_buffer.clear(); } is_recipe.close(); return 0; } void RecipeReader::processNewlineEscapes(string &s_string, ifstream &is_stream) { string s_temp; size_t sz_index = s_string.find_first_of("\\"); while (sz_index <= s_string.length()) { if (getline(is_stream,s_temp)) { removeLeadingWhitespace(s_temp); processComment(s_temp); s_string = s_string.substr(0,sz_index-1) + " " + s_temp; } else cout << "Error: newline escape '\' found at EOF" << endl; sz_index = s_string.find_first_of("\\"); } } void RecipeReader::processComment(string &s_string) { size_t sz_index = s_string.find_first_of("#"); s_string = s_string.substr(0,sz_index); } void RecipeReader::removeLeadingWhitespace(string &s_string) { const size_t sz_length = s_string.size(); size_t sz_index = s_string.find_first_not_of(" \t"); if (sz_index <= sz_length) s_string = s_string.substr(sz_index); else if ((sz_index > sz_length) && (sz_length != 0)) // "empty" lines with only whitespace s_string.clear(); } Some extra info: the first s_buffer passed to the ifstream contains the filename, std::string s_buffer is a class data member, so is std::vector v_s_recipe. Any comment is welcome :) UPDATE: for the sake of not being ungrateful, here is my replacement, all-in-one function that does what I want for now (future holds: parenthesis, maybe quotes...): void readRecipe(const std::string &filename) { string buffer; string line; size_t index; ifstream file(filename.c_str()); if (!file) throw runtime_error("Unable to open file."); while (getline(file, line)) { // whitespace removal line.erase(0, line.find_first_not_of(" \t\r\n\v\f")); // comment removal TODO: store these for later output index = line.find_first_of("#"); if (index != string::npos) line.erase(index, string::npos); // ignore empty buffer if (line.empty()) continue; // process newline escapes index = line.find_first_of("\\"); if (index != string::npos) { line.erase(index,string::npos); // ignore everything after '\' buffer += line; continue; // read next line } else // no newline escapes found { buffer += line; recipe.push_back(buffer); buffer.clear(); } } }
A few comments: As another answer (+1 from me) said - ditch the hungarian notation. It really doesn't do anything but add unimportant trash to every line. In addition, ifstream yielding an is_ prefix is ugly. is_ usually indicates a boolean. Naming a function with processXXX gives very very little information on what it is actually doing. Use removeXXX, like you did with the RemoveLeadingWhitespace function. The processComment function does an unnecessary copy and assignment. Use s.erase(index, string::npos); (npos is default, but this is more obvious). It's not clear what your program does, but you might consider storing a different file format (like html or xml) if you need to post-process your files like this. That would depend on the goal. using find_first_of('#') may give you some false positives. If it's present in quotes, it's not necessarily indicating a comment. (But again, this depends on your file format) using find_first_of(c) with one character can be simplified to find(c). The processNewlineEscapes function duplicates some functionality from the readRecipe function. You may consider refactoring to something like this: - string s_buffer; string s_line; while (getline(is_recipe, s_line)) { // Sanitize the raw line. removeLeadingWhitespace(s_line); removeComments(s_line); // Skip empty lines. if (s_line.empty()) continue; // Add the raw line to the buffer. s_buffer += s_line; // Collect buffer across all escaped lines. if (*s_line.rbegin() == '\\') continue; // This line is not escaped, now I can process the buffer. v_s_recipe.push_back(s_buffer); s_buffer.clear(); }
2,888,749
2,888,787
Storing data with a stand-alone C++ application
I work with Apache, PHP, and MySQL for web development and local applications. For the past couple of years I have slowly been learning C++ and want to build an application this summer. Specifically, I want to make a "library" application in which I can store information about the books, CDs, and records that I own. I know this type of app exists, but I want to learn C++ and this seems like a good way to go about it. Here are a few questions: Is it possible to create a stand-alone application that does not require a database for storing data? If the answer to #1 above is "yes", is it a good idea to do this for an application that could potentially need to manage a lot of data? What data-storage options would you recommend for use with a C++ application? Thanks! Update Well, there were a lot of good answers to this. This is such a great site with so many contributors. It turns out that I might not really need to go the C++ route for now. I now realize that I am most interested in writing an application that can function as a "library" organizational system more than I want to pursue C++. Thanks to everybody for your answers!
Is it possible to create a stand-alone application that does not require a database for storing data? Yes, you could do some sort of custom file format for storing data. If the answer to #1 above is "yes", is it a good idea to do this for an application that could potentially need to manage a lot of data? It's not really a good idea, unless you really want to learn about storing data in a structured file. What data-storage options would you recommend for use with a C++ application? I'd look at SQLite. It is a database, but it doesn't need a separate engine.
2,888,805
2,888,808
static const C++ class member initialized gives a duplicate symbol error when linking
I have a class which has a static const array, it has to be initialized outside the class: class foo{ static const int array[3]; }; const int foo::array[3] = { 1, 2, 3 }; But then I get a duplicate symbol foo::array in foo.o and main.o foo.o hold the foo class, and main.o holds main() and uses instances of foo. How can I share this static const array between all instances of foo? I mean, that's the idea of a static member.
Initialize it in your corresponding .cpp file not your .h file. When you #include it's a pre-processor directive that basically copies the file verbatim into the location of the #include. So you are initializing it twice by including it in 2 different compilation units. The linker sees 2 and doesn't know which one to use. If you had only initialized it in one of the source files, only one .o would contain it and you wouldn't have a problem.
2,888,843
2,888,849
syntax error : missing ';' before identifier
I am new to c++, trying to debug the following line of code class cGameError { string m_errorText; public: cGameError( char *errorText ) { DP1("***\n*** [ERROR] cGameError thrown! text: [%s]\n***\n", errorText ); m_errorText = string( errorText ); } const char *GetText() { return m_errorText.c_str(); } }; enum eResult { resAllGood = 0, // function passed with flying colors resFalse = 1, // function worked and returns 'false' resFailed = –1, // function failed miserably resNotImpl = –2, // function has not been implemented resForceDWord = 0x7FFFFFFF }; This header file is included in the program as followed #include "string.h" #include "stdafx.h" #include "Chapter 01 MyVersion.h" #include "cGameError.h"
You need to include <string>, not "string.h". Or in addition to "string.h". string.h is the C header for the standard C string handling functions (strcpy() and friends.) <string> is the standard C++ header where 'string' is defined. You also need to specify the std namespace when using string: std::string m_errorText; Or by using: using namespace std; Somewhere at the top of your file. You should also use angle brackets for system include files.
2,888,906
2,889,044
C++ bughunt - High-score insertion in a vector crashes the program
I have a game I'm working on. My players are stored in a vector, and, at the end of the game, the game crashes when trying to insert the high-scores in the correct positions. Here's what I have (please ignore the portuguese comments, the code is pretty straightforward :P): //TOTAL_HIGHSCORES is the max. number of hiscores that i'm willing to store. This is set as 10. bool Game::updateHiScores() { bool stopIterating; bool scoresChanged = false; //Se ainda nao existirem TOTAL_HISCORES melhores pontuacoes ou se a pontuacao for melhor que uma das existentes for (size_t i = 0; i < players.size(); ++i) { if (hiScores.empty()) checkForValues = true; else checkForValues = (hiScores.size() < TOTAL_HISCORES || hiScores.back() < players[i].getScore()); if (players[i].getScoreValue() > 0 && checkForValues) { scoresChanged = true; if(hiScores.empty() || hiScores.back() >= players[i].getScore()) hiScores.push_back(players[i].getScore()); else { //Ciclo que encontra e insere a pontuacao no lugar desejado stopIterating = false; for(vector<Score>::iterator it = hiScores.begin(); it < hiScores.end() && !(stopIterating); ++it) { if(*it <= players[i].getScore()) { //E inserida na posicao 'it' o Score correspondente hiScores.insert(it, players[i].getScore()); //Verifica se o comprimento do vector esta dentro do desejado, se nao estiver, este e rectificado if (hiScores.size() > TOTAL_HISCORES) hiScores.pop_back(); stopIterating = true; } } } } } if (scoresChanged) sort(hiScores.begin(), hiScores.end(), higher); return scoresChanged; } What am I doing wrong here? Thanks for your time, fellas. EDIT: I ended up simplifying my code to this: bool scoresChanged; vector<Score> hiScoresCopy = hiScores; for (size_t i = 0; i < TOTAL_PLAYERS; ++i) hiScoresCopy.push_back(players[i].getScore()); sort(hiScoresCopy.begin(), hiScoresCopy.end(), higher); scoresChanged = (hiScores != hiScoresCopy); if (scoresChanged) { if (hiScoresCopy.size() > TOTAL_HISCORES) hiScoresCopy.resize(TOTAL_HISCORES); hiScores = hiScoresCopy; } return scoresChanged;
You don't say exactly where the code crashes or what the nature of the crash so I shall guess. This test is the wrong way around. it < hiScores.end() && !(stopIterating) In one common case your iterator it will be invalidated in the same clause that you set stopIterating to true. You could do this (!= is more idiomatic than < for iterators although both work for vectors). !stopIterating && it != hiScores.end() Alternatively, after your insertion you could just have break; statement and do away with the stopIterating variable. I think that this would be clearer for most readers of the code.
2,889,074
2,889,093
Output spits two extra control characters, possibly a memory corruption bug?
I have the following program test.cc: #include <iostream> unsigned char bogus1[] = { // Changing # of periods (0x2e) changes output after periods. 0x2e, 0x2e, 0x2e, 0x2e }; unsigned int bogus2 = 1816; // Changing this value changes output. int main() { std::clog << bogus1; } I build it with: g++ -g -c -o test.o test.cc; g++ -static-libgcc -o test test.o Using g++ version 3.4.6 I run it through valgrind and nothing is reported wrong. However the output has two extra control characters and looks like this: .... That's a control-X and a control-G at the end. If you change the value of bogus2 you get different control characters. If you change the number of periods in the array the issue goes away or changes. I suspect it is a memory corruption bug in the compiler or iostream package. What is going on here?
In C/C++, a string is usually stored as a null-terminated char array. Your unsigned char array isn't null-terminated. Usually it would look something like this: unsigned char bogus1[] = { 0x2e, 0x2e, 0x2e, 0x2e, 0x00 // terminating NUL byte }; If it isn't null-terminated, output will continue until a NUL byte is found, that's why it outputs values that are placed in the memory behind your array, like the int bogus2 (which is 0x00000718 in hex, stored in little endian format => 0x18 = Ctrl-X, 0x07 = Ctrl-G, 0x00 ends the output)
2,889,182
2,889,495
writing structs and classes to disk
The following function writes a struct to a file. #define PAGESIZE sizeof(BTPAGE) #define HEADERSIZE 2L int btwrite(short rrn, BTPAGE *page_ptr) { long addr; addr = (long) rrn * (long) PAGESIZE + HEADERSIZE; lseek(btfd, addr, 0); return (write(btfd, page_ptr, PAGESIZE)); } The following is the struct. typedef struct { short keycount; /* number of keys in page */ int key[MAXKEYS]; /* the actual keys */ int value[MAXKEYS]; /* the actual values */ short child[MAXKEYS+1]; /* ptrs to rrns of descendants */ } BTPAGE; What would happen if I changed the struct to a class, would it still work the same? If I added class functions, would the size it takes up on disk increase?
There's a lot you need to learn here. First of all, you're treating a structure as an array of bytes. This is strictly undefined behavior due to the strict aliasing rule. Anything can happen. So don't do it. Use proper serialization (for example via boost) instead. Yes, it's tedious. Yes, it's necessary. Even if you ignore the undefinedness, and choose to become dependant on some particular compiler implementation (which may change even in the next compiler version), there's still reasons not to do it. If you save a file on one machine, then load it on another, you may get garbage, because the second machine uses a different float representation, or a different endianness, or has different alignment rules, etc. If your struct contains any pointers, it's very likely that saving them verbatim then loading them back will result in an address that doesn't not point to any meaningful place. Typically when you add a member function, this happens: the function's machine code is stored in a place shared by all the class instances (it wouldn't make sense to duplicate it, since it's logically immutable) a hidden "this" pointer is passed to the function when it's called, so it knows which object it's been called on. none of this requires any storage space in the instances. However, when you add at least one virtual function, the compiler typically needs to also add a data chunk called a vtable (read up on it). This makes it possible to call different code depending on the current runtime type of the object (aka polymorphism). So the first virtual function you add to the class likely does increase the object size.
2,889,186
2,889,191
Should I set global vars value on startup or the first time I use them? C++
I have a few global vars I need to set the value to, should I set it into the main/winmain function? or should I set it the first time I use each var?
Instead, how about not using global variables at all? Pass the variables as function parameters to the functions that need them, or store pointers or references to them as members of classes that use them.
2,889,202
2,889,226
Is there a way to introspect an array's size?
In C++ given an array like this: unsigned char bogus1[] = { 0x2e, 0x2e, 0x2e, 0x2e }; Is there a way to introspect bogus1 to find out is is four characters long?
Sure: #include <iostream> int main() { unsigned char bogus1[] = { 0x2e, 0x2e, 0x2e, 0x2e }; std::cout << sizeof(bogus1) << std::endl; return 0; } emits 4. More generally, sizeof(thearray)/sizeof(thearray[0]) is the number of items in the array. However, this is a compile-time operation and can only be used where the compiler knows about that "number of items" (not, for example, in a function receiving the array as an argument). For more generality, you can use std::vector instead of a bare array.
2,889,232
2,889,241
How to make a struct of structs in C++
Can a struct contain other structs? I would like to make a struct that holds an array of four other structs. Is this possible? What would the code look like?
Yes, you can. For example, this struct S2 contains an array of four S1 objects: struct S1 { int a; }; struct S2 { S1 the_array[4]; };
2,889,273
2,889,500
How to build boost::asio example?
I'm trying to build an example of boost::asio http://www.boost.org/doc/libs/1_43_0/doc/html/boost_asio/example/echo/async_tcp_echo_server.cpp but without any luck. System: Windows Vista, Visual C++ 2008 Pro, Boost 1.43. I've added to the project, at VC, the include path and the additional lib path (see note #1), yet the linker gives me this error: 1>LINK : fatal error LNK1104: cannot open file 'libboost_system-vc90-mt-gd-1_43.lib' What do I do next? In the documentation (the "getting started" part) it says that some boost's components must be built separately. Ok. How do I do this and where do I find them? In the "getting started" page there's the section "6.1 Link From Within the Visual Studio IDE". It just tells me how to link, and not how to build it. Anyone can shed some light? Because I am definitely missing something here. Note #1: There's not "boost_1_43_0/lib" folder but a "libs". The doc needs a refresh.
Check out this, I needed to re-phrase in order to get an answer: fatal error LNK1104: cannot open file 'libboost_system-vc90-mt-gd-1_43.lib' Thank you all!
2,889,337
2,889,346
Why does this C++ char array seem to be able to hold more than its size?
#include <iostream> using namespace std; typedef struct { char streetName[5]; } RECORD; int main() { RECORD r; cin >> r.streetName; cout << r.streetName << endl; } When I run this program, if I enter in more than 5 characters, the output will show the whole string I entered. It does not truncate at 5 characters. Why is that? How can I get this to work correctly?
You are overflowing the buffer. Put another char array after streetName and you will likely find that it gets the rest of the characters. Right now you are just corrupting some memory on your stack.
2,889,392
2,889,484
Adding C++ DLL's to a C# project
I'm trying to use the lame_enc.dll file from LAME in a C# project, but adding the thing seems impossible. I keep getting an error that says that a reference could not be added and to please check if the is accessible, a valid assembly or COM component. I have no C++ experience, though I would like to use the functionality. Right now I'm using Process from the .NET framework to call lame.exe and do stuff, but I'd like to know if there's another way.
You have to use P/Invoke to call unmanaged APIs from managed code.
2,889,394
2,889,409
fatal error LNK1104: cannot open file 'libboost_system-vc90-mt-gd-1_43.lib'
Made a new project, added main.cpp and wrote the code at this URL: http://www.boost.org/doc/libs/1_43_0/doc/html/boost_asio/example/echo/async_tcp_echo_server.cpp Also, added the appropriate include path. What's next?!?!! It seems like a darn mystery to build a boost code! Been digging on it for more than 10 hours. Can anyone give a straightforward answer on how to build the boost library from the code under windows, VC9?
You need to use bjam. It is responsible for creating the libraries that your application will use. Once you use bjam, you are going to need to instruct your project to include the lib file. You do this by going into the project's properties -> Configuration Properties -> Linker -> General. Add the directory which created the lib file to Additional Library Directories. You should be capable of correctly linking after that. I believe that this link describes the steps better than I could attempt in a post
2,889,421
2,889,483
How to copy a string into a char array in C++ without going over the buffer
I want to copy a string into a char array, and not overrun the buffer. So if I have a char array of size 5, then I want to copy a maximum of 5 bytes from a string into it. what's the code to do that?
First of all, strncpy is almost certainly not what you want. strncpy was designed for a fairly specific purpose. It's in the standard library almost exclusively because it already exists, not because it's generally useful. Probably the simplest way to do what you want is with something like: sprintf(buffer, "%.4s", your_string.c_str()); Unlike strncpy, this guarantees that the result will be NUL terminated, but does not fill in extra data in the target if the source is shorter than specified (though the latter isn't a major issue when the target length is 5).
2,889,771
2,889,794
How to extract comment out of header file using python, perl, or sed?
I have a header file like this: /* * APP 180-2 ALG-254/258/772 implementation * Last update: 03/01/2006 * Issue date: 08/22/2004 * * Copyright (C) 2006 Somebody's Name here * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef HEADER_H #define HEADER_H /* More comments and C++ code here. */ #endif /* End of file. */ And I wish to extract out the contents of the first C style comment only and drop the " *" at the start of each line to get a file with the following contents: APP 180-2 ALG-254/258/772 implementation Last update: 03/01/2006 Issue date: 08/22/2004 Copyright (C) 2006 Somebody's Name here All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Please suggest an easy way to do this with Python, Perl, sed, or some other way on Unix. Preferably as a one-liner.
This should work for you: sed -n '/\*\//q; /^\/\*/d; s/^ \* \?//p' <file.h >comment.txt Here's an explanation: sed (as you may know) is a command that goes through a file applying a list of rules to each line. Each rule consists of a "selector" and commands that are applied to that line only if the selector matches. The first rule has the selector /\*\//. This is a regular expression selector; it matches any line that contains the characters */. Both of these need to be backslash-escaped since they have special meanings in a regexp. (I've assumed that this will only match the closing line of the comment in your case and that this entire line should be deleted.) The command is q which means "quit." sed just stops. Ordinarily it would print out the line, but I provided the -n option which means "don't print unless explicitly instructed to." The second rule has the selector /^\/\*/ which is again a regexp selector that matches the characters /* at the start of the line. Again, I've assumed this line will not contain part of the comment. The d command tells sed to delete this line and move on. The final rule has no selector, so it applies to all lines (unless a previous command prevented processing from reaching the final rule). The command in this last rule is a substitution command, s/PATTERN/REPLACEMENT/, which finds text in the line that matches some pattern and replaces it with a replacement text. The pattern here is ^ \* \?, which matches a space, an asterisk, and either 0 or 1 spaces, but only at the beginning of the line. And the replacement is nothing. So sed simply deletes the leading space-asterisk-(space)? sequence. The p is actually a flag to the substitution command that tells sed to print out the result of the substitution. It's needed because of the -n option.
2,889,964
2,889,990
creating thread on another core? (WinAPI)
I was wondering if there was a way to run a thread on a seperate core instead of just a thread on that core? Thanks
If you create a thread, you have by default no control on which core it will run. The operation system's scheduling algorithm takes care of that, and is pretty good at its job. However, you can use the SetThreadAffinity WinAPI to specify the logical cores a thread is allowed to run on. Don't do that unless you have very good reasons. Quoting MSDN: Setting an affinity mask for a process or thread can result in threads receiving less processor time, as the system is restricted from running the threads on certain processors. In most cases, it is better to let the system select an available processor.
2,890,001
2,890,008
Graph - strongly connected components
Is there any fast way to determine the size of the largest strongly connected component in a graph? I mean, like, the obvious approach would mean determining every SCC (could be done using two DFS calls, I suppose) and then looping through them and taking the maximum. I'm pretty sure there has to be some better approach if I only need to have the size of that component and only the largest one, but I can't think of a good solution. Any ideas? Thanks.
Let me answer your question with another question - How can you determine which value in a set is the largest without examining all of the values?
2,890,320
2,890,355
can these templates be made unambiguous
I'm trying to create a set of overloaded templates for arrays/pointers where one template will be used when the compiler knows the size of the array and the other template will be used when it doesn't: template <typename T, size_t SZ> void moo(T (&arr)[SZ]) { ... } template <typename T> void moo(T *ptr) { ... } The problem is that when the compiler knows the size of the array, the overloads are ambiguous and the compile fails. Is there some way to resolve the ambiguity (perhaps via SFINAE) or is this just not possible.
It is possible as it can be determined wether a template parameter is an array or not: template<class T> struct is_array { enum { value = false }; }; template<class T, size_t N> struct is_array<T[N]> { enum { value = true }; }; template<class T> void f(T const&) { std::cout << is_array<T>::value << std::endl; } Combining that with enable_if, the above can be made unambiguous. For example using Boost.TypeTraits: template <typename T, size_t SZ> typename boost::enable_if<boost::is_array<T>, void>::type f(T (&arr)[SZ]) {} With references however there is no need for SFINAE at all: template<class T, size_t SZ> void f(T (&arr)[SZ]) {} template<class T> void f(T* const& t) {} Johannes brings up another option that fits the situation at hand better - using SFINAE for the problematic pointer overload instead: template <typename T, size_t SZ> void f(T (&arr)[SZ]) {} template <typename T> typename boost::enable_if<boost::is_pointer<T>, void>::type f(T ptr) {}
2,890,408
2,890,428
Is there a var type equivalent in C++?
So I know that C++ is strongly typed and was just wondering if there was any library (or any thing for that fact of the matter) that would allow you to make a variable that has no initial specific type like var in Python.
Take a look at boost::any and boost::variant.
2,890,525
2,890,537
Sorting odd in descending and even in ascending order
Given a array of random integers, sort the odd elements in descending order and even numbers in ascending order. Example input: (1,4,5,2,3,6,7) Output: (7,5,3,1,2,4,6) Optimize for time complexity.
Which language is it, C or C++ (I see both tags) In C++, you can use std::sort() with appropriate ordering function. In C, qsort() works similarly: #include <iostream> #include <algorithm> bool Order(int a, int b) { if (a%2 != b%2) return a%2; else return a%2 ? b<a : a<b; } int main() { int a[] = {1,4,5,2,3,6,7}; size_t N = sizeof(a) / sizeof(a[0]); std::sort(a, a+N, Order); for(size_t i=0; i<N; ++i) std::cout << a[i] << ' '; std::cout << std::endl; }
2,890,536
2,890,543
c++ passing unknown type to a function and any Class type definition
I am trying to create a generic class to write and read Objects to/from file. Called it ActiveRecord class only has one method, which saves the class itself: void ActiveRecord::saveRecord(){ string fileName = "data.dat"; ofstream stream(fileName.c_str(), ios::out); if (!stream) { cerr << "Error opening file: " << fileName << endl; exit(1); } stream.write(reinterpret_cast<const char *> (this), sizeof(ActiveRecord)); stream.close(); } now I'm extending this class with User class: class User : public ActiveRecord { public: User(void); ~User(void); string name; string lastName; }; to create and save the user I would like to do something like: User user = User(); user.name = "John"; user.lastName = "Smith" user.save(); how can I get this ActiveRecord::saveRecord() method to take any object, and class definition so it writes whatever i send it: to look like: void ActiveRecord::saveRecord(foo_instance, FooClass){ string fileName = "data.dat"; ofstream stream(fileName.c_str(), ios::out); if (!stream) { cerr << "Error opening file: " << fileName << endl; exit(1); } stream.write(reinterpret_cast<const char *> (foo_instance), sizeof(FooClass)); stream.close(); } and while we're at it, what is the default Object type in c++. eg. in objective-c it's id in java it's Object in AS3 it's Object what is it in C++??
stream.write(reinterpret_cast<const char *> (foo_instance), sizeof(FooClass)); This doesn't work. string allocates its data on the heap (IIRC, when it's larger than 16chars). Your reinterpret cast will not include that heap data. Don't reinvent the wheel, this is a non-trivial, but solved problem. Use Google Protocol Buffers, XML, or the boost serialization library. What you have in mind is templates, but you can't "just serialize any object" because outside of POD (plain-old-data) types, their representation isn't obvious. In addition, using sizeof(BaseClass) with the User subclass will not work. It'll slice the subclass's member data off of the cast and not put it in the file. And there is no "default Object type in c++".
2,890,588
2,890,596
Weird characters at the beginning of a LPTSTR? C++
I am using this code to get the windows version: #define BUFSIZE 256 bool config::GetOS(LPTSTR OSv) { OSVERSIONINFOEX osve; BOOL bOsVersionInfoEx; ZeroMemory(&osve, sizeof(OSVERSIONINFOEX)); osve.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); if( !(bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osve)) ) return false; TCHAR buf[BUFSIZE]; StringCchPrintf(buf, BUFSIZE, TEXT("%u.%u.%u.%u"), osve.dwPlatformId, osve.dwMajorVersion, osve.dwMinorVersion, osve.dwBuildNumber); StringCchCat(OSv, BUFSIZE, buf); return true; } And I am testing it with: LPTSTR OSv= new TCHAR[BUFSIZE]; config c; c.GetOS(OSv); MessageBox(OSv, 0, 0); And in the msgbox I get something like this äì5.1.20 (where 5.1.20 is = to OSv) but the first 2 or 3 chars are some weird characters that I don't know when they came from. Even stranger, if I call that second piece again it shows it ok, it only show the weird characters the first time I execute it. Does someone has an idea what's going on here?
Your problem is that you should be using StringCchCopy and not StringCchCat. StringCchCat will search until it finds a 0 in the string, and then append the result there. Since you are not initializing your output string buffer to 0's, you cannot assume it will start with a 0.
2,890,589
2,890,599
C++ destructors causing crash's
ok, so i got a some what intricate program that simulates the uni systems of students, units, and students enrolling in units. Students are stored in a binary search tree, Units are stored in a standard list. Student has a list of Unit Pointers, to store which units he/she is enrolled in Unit has a list of Student pointers, to store students which are enrolled in that unit. The unit collections (storing units in a list) as made as a static variable where the main function is, as is the Binary search tree of students. when its finaly time to close the program, i call the destructors of each. but at some stage, during the destructors on the unit side, Unhandled exception at 0x002e4200 in ClassAllocation.exe: 0xC0000005: Access violation reading location 0x00000000. UnitCollection destructor: UnitCol::~UnitCol() { list<Unit>::iterator itr; for(itr = UnitCollection.begin(); itr != UnitCollection.end();) { UnitCollection.pop_front(); itr = UnitCollection.begin(); } } Unit Destructor Unit::~Unit() { } now i got the same sorta problem on the student side of things BST destructors void StudentCol::Destructor(const BTreeNode * r) { if(r!= 0) { Destructor(r->getLChild()); Destructor(r->getRChild()); delete r; } } StudentCol::~StudentCol() { Destructor(root); } Student Destructor Student::~Student() { } so yeah any help would be greatly appreciated
If your UnitCollection is std::list<Unit> then you don't have to manually remove items - the list itself with destroy contained objects and deallocate the memory in its own destructor. Take a look at std::list documentation. I would also suggest that you post complete code - some of your description is contradictory.
2,890,635
2,898,013
Error with Phoenix placeholder _val in Boost.Spirit.Lex :(
I'm newbie in Boost.Spirit.Lex. Some strange error appears every time I try to use lex::_val in semantics actions in my simple lexer: #ifndef _TOKENS_H_ #define _TOKENS_H_ #include <iostream> #include <string> #include <boost/spirit/include/lex_lexertl.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include <boost/spirit/include/phoenix_statement.hpp> #include <boost/spirit/include/phoenix_container.hpp> namespace lex = boost::spirit::lex; namespace phx = boost::phoenix; enum tokenids { ID_IDENTIFICATOR = 1, ID_CONSTANT, ID_OPERATION, ID_BRACKET, ID_WHITESPACES }; template <typename Lexer> struct mega_tokens : lex::lexer<Lexer> { mega_tokens() : identifier(L"[a-zA-Z_][a-zA-Z0-9_]*", ID_IDENTIFICATOR) , constant (L"[0-9]+(\\.[0-9]+)?", ID_CONSTANT ) , operation (L"[\\+\\-\\*/]", ID_OPERATION ) , bracket (L"[\\(\\)\\[\\]]", ID_BRACKET ) { using lex::_tokenid; using lex::_val; using phx::val; this->self = operation [ std::wcout << val(L'<') << _tokenid // << val(L':') << lex::_val << val(L'>') ] | identifier [ std::wcout << val(L'<') << _tokenid << val(L':') << _val << val(L'>') ] | constant [ std::wcout << val(L'<') << _tokenid // << val(L':') << _val << val(L'>') ] | bracket [ std::wcout << val(L'<') << _tokenid // << val(L':') << lex::_val << val(L'>') ] ; } lex::token_def<wchar_t, wchar_t> operation; lex::token_def<std::wstring, wchar_t> identifier; lex::token_def<double, wchar_t> constant; lex::token_def<wchar_t, wchar_t> bracket; }; #endif // _TOKENS_H_ and #include <cstdlib> #include <iostream> #include <locale> #include <boost/spirit/include/lex_lexertl.hpp> #include "tokens.h" int main() { setlocale(LC_ALL, "Russian"); namespace lex = boost::spirit::lex; typedef std::wstring::iterator base_iterator; typedef lex::lexertl::token < base_iterator, boost::mpl::vector<wchar_t, std::wstring, double, wchar_t>, boost::mpl::true_ > token_type; typedef lex::lexertl::actor_lexer<token_type> lexer_type; typedef mega_tokens<lexer_type>::iterator_type iterator_type; mega_tokens<lexer_type> mega_lexer; std::wstring str = L"alfa+x1*(2.836-x2[i])"; base_iterator first = str.begin(); bool r = lex::tokenize(first, str.end(), mega_lexer); if (r) { std::wcout << L"Success" << std::endl; } else { std::wstring rest(first, str.end()); std::wcerr << L"Lexical analysis failed\n" << L"stopped at: \"" << rest << L"\"\n"; } return EXIT_SUCCESS; } This code causes an error in Boost header 'boost/spirit/home/lex/argument.hpp' on line 167 while compiling: return: can't convert 'const boost::variant' to 'boost::variant &' When I don't use lex::_val program compiles with no errors. Obviously, I use _val in wrong way, but I do not know how to do this correctly. Help, please! :) P.S. And sorry for my terrible English…
I believe this is a problem in the current Phoenix related to using iostreams. As a workaround I suggest to define a custom (Phoenix) function doing the actual output: struct output_operation_impl { template <typename TokenId, typename Val> struct result { typedef void type; }; template <typename TokenId, typename Val> void operator()(T1 const& tokenid, T2 const& val) const { std::wcout << L'<' << tokenid << L':' << val << L'>'; } }; boost::phoenix::function<output_operation_impl> const output_operation = output_operation_impl(); calling it as: this->self = operation[ output_operation(_tokenid, _val) ] ... ; Regards Hartmut
2,890,722
2,890,728
Including huge string in our c++ programs?
I am trying to include huge string in my c++ programs, Its size is 20598617 characters , I am using #define to achieve it. I have a header file which contains this statement #define "<huge string containing 20598617 characterd>" When I try to compile the program I get error as fatal error C1060: compiler is out of heap space I tried following command line options with no success /Zm200 /Zm1000 /Zm2000 How can I make successful compilation of this program? Platform: Windows 7
You can't, not reliably. Even if it will compile, it's liable to break the runtime library, or the OS assumptions, and so forth. If you tell us why you're trying to do it, we can offer lots of alternatives. Deciding how to handle arbitrarily large data is a major part of programming. Edited to add: Rather than guess, I looked into MSDN: Prior to adjacent strings being concatenated, a string cannot be longer than 16380 single-byte characters. A Unicode string of about one half this length would also generate this error. The page concludes: You may want to store exceptionally large string literals (32K or more) in a custom resource or an external file. What do other compilers say? Further edited to add: I created a file like this: char s[] = {'x','x','x','x'}; I kept doubling the occurrences of 'x', testing each one as an #include file. An 8388608 byte string succeeded; 16777216 bytes failed, with the "out of heap space" error.
2,890,811
2,890,816
handling large number
This is Problem 3 from Project Euler site I'm not out after the solution, but I probably guess you will know what my approach is. To my question now, how do I handle numbers exceeding unsigned int? Is there a mathematical approach for this, if so where can I read about it?
Have you tried unsigned long long or even more better/specifically uint64_t? If you want to work with numbers bigger than the range of uint64_t [264-1] [64 bit integer, unsigned], then you should look into bignum: http://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic. 600,851,475,143 is the number given by the question and 264-1 is equal to 18,446,744,073,709,551,615. It is definitely big enough.
2,890,860
2,890,867
C++ error: ‘string’ has not been declared
In my header file I'm getting the error: ‘string’ has not been declared error but at the top of the file I have #include <string>, so how can I be getting this error?
string resides in the std namespace, you have to use std::string or introduce it into the scope via using directives or using declarations.
2,891,166
2,894,290
Pages used by a DLL in the address space of a process
Is there a reliable way to learn that a memory page or a range of pages belongs to a specific DLL inside the address space of a process?
There are a method known as API hooking. Well known BugslayerUtil.DLL from John Robbins (see his book "Debugging Applications") war used originally as API hooking inside own process. I mean that all memory allocation can be allocated with respect of small number of well known functions like LocalAlloc, GlobalAlloc, VirtualAlloc etc. One can overwrite start addresses of this functions inside of process address space. You can do this either somewhere at the beginning of the process or use DLL Injection to make this (like it do Dependency Walker in profiling mode). So you will be able to log (trace) every memory allocation attempt, forward the call to the original function, see the resulting return values log (trace) one more time and gives results back. Inside of every call attempt you can see all functions which called this one on the call stack. So the contain of the call stack together with the address of allocated memory and the size gives you full information for which your are looking for. You will see all in the dynamic. You should not implement all stuffs yourself. Just search in internet for "API hooking" or "DLL injection" and you will find enough working examples. For examining of the call stack you can use documented StackWalk64 function (see http://msdn.microsoft.com/en-us/library/ms680650(VS.85).aspx) from imagehlp.dll / dbghelp.dll (for example see http://www.codeproject.com/KB/threads/StackWalker.aspx). So it seems to me that your problem could be solved.
2,891,275
2,891,308
How to fill a section within c++ string?
Having a string of whitespaces: string *str = new string(); str->resize(width,' '); I'd like to fill length chars at a position. In C it would look like memset(&str[pos],'#', length ); How can i achieve this with c++ string, I tried string& assign( const string& str, size_type index, size_type len ); but this seems to truncat the original string. Is there an easy C++ way to do this? Thanks.
In addition to string::replace() you can use std::fill: std::fill(str->begin()+pos, str->begin()+pos+length, '#'); //or: std::fill_n(str->begin()+pos, length, '#'); If you try to fill past the end of the string though, it will be ignored.
2,891,344
2,891,453
Visual studio feature - commenting code Ctrl K - Ctrl C
I commented on this answer some time ago regarding how visual studio comments out code with // or /* */. I was thinking to revise the answer (to include my findings) but I had to test it first, which kind of confused me. My finding is that depending on what you comment when you press Ctrl - K, Ctrl - C you will get either // or /* */. First example: <start selection here> code(); someCall(); thirdCall();<end selection here> this will produce the following: //code(); //someCall(); //thirdCall(); Second example: <start selection here>code(); someCall(); thirdCall();<end selection here> this will produce the following: /*code(); someCall(); thirdCall();*/ Third example <start selection here>code(); //someCall(); thirdCall();<end selection here> this will produce the following: //code(); ////someCall(); //thirdCall(); Note that example 2 and 3 is the exact same selection, but the comment makes Visual Studio interpret it differently. Why is this?
The approach one would expect is to use // for any selection that is made up entirely of complete lines, and /*...*/ for anything that starts/ends mid-way along a line. ...which is what it seems to actually do.
2,891,525
2,891,620
Finding the maximum weight subsequence of an array of positive integers?
I'm tring to find the maximum weight subsequence of an array of positive integers - the catch is that no adjacent members are allowed in the final subsequence. The exact same question was asked here, and a recursive solution was given by MarkusQ thus: function Max_route(A) if A's length = 1 A[0] else maximum of A[0]+Max_route(A[2...]) Max_route[1...] He provides an explanation, but can anyone help me understand how he has expanded the function? Specifically what does he mean by f[] :- [],0 f [x] :- [x],x f [a,b] :- if a > b then [a],a else [b],b f [a,b,t] :- ft = f t fbt = f [b|t] if a + ft.sum > fbt.sum [a|ft.path],a+ft.sum else fbt Why does he expand f[] to [],0? Also how does his solution take into consideration non-adjacent members? I have some C++ code that is based on this algorithm, which I can post if anyone wants to see it, but I just can't for the life of me fathom why it works. ==========For anyone who's interested - the C++ code ============== I should add, that the array of integers is to be treated as a circular list, so any sequence containing the first element cannot contain the last. int memo[55][55]; int solve(int s, int e) { if( s>e ) return 0; int &ret=memo[s][e]; if(ret!=-1) { return ret; } ret=max(solve(s+1,e), solve(s+2,e)+a[s]); return ret; } class Sequence { public: int maxSequence(vector <int> s) { memset(memo,-1); int n = s.size(); for(int i=0; i<n; i++) a[i]=s[i]; return max(solve(0,n-2),solve(1,n-1)); } };
I don't really understand that pseudocode, so post the C++ code if this isn't helpful and I'll try to improve it. I'm tring to find the maximum weight subsequence of an array of positive integers - the catch is that no adjacent members are allowed in the final subsequence. Let a be your array of positive ints. Let f[i] = value of the maximum weight subsequence of the sequence a[0..i]. We have: f[0] = a[0] because if there's only one element, we have to take it. f[1] = max(a[0], a[1]) because you have the no adjacent elements restriction, so if you have two elements, you can only take one of them. It makes sense to take the largest one. Now, generally you have: f[i > 1] = max( f[i - 2] + a[i] <= add a[i] to the largest subsequence of the sequence a[0..i - 2]. We cannot take a[0..i - 1] because otherwise we risk adding an adjacent element. f[i - 1] <= don't add the current element to the maximum of a[0..i - 2], instead take the maximum of a[0..i - 1], to which we cannot add a[i]. ) I think this way is easier to understand than what you have there. The approaches are equivalent, I just find this clearer for this particular problem, since recursion makes things harder in this case and the pseudocode could be clearer either way.
2,891,596
2,930,981
MySQL Connector Linker Problem
Hey, I'm trying to compile a program with the MySQL C++ Connector but somehow I can't get the linking right. The errors I get are: mysql/lib/libmysqlcppconn.so: undefined reference to `std::ios_base::ios_base()@GLIBCPP_3.2'.... etc alt text http://img156.imageshack.us/img156/4022/linking.th.png locations: libmysqlcppconn.so: mysql/lib/ libmysqlclient.so: /usr/lib/ I tried to follow the tutorial on mysql and some other pages but the results where the same, maybe I missed something.
OK, it seems like the connector (binary) requires a certain libstdc++.so version (5) since I couldn't fix that I had to use the sources. Some errors I encountered while compiling them where that I had to include <stdio.h>. Now Everything is working!
2,891,690
2,891,732
Closure and nested lambdas in C++0x
Using C++0x, how do I capture a variable when I have a lambda within a lambda? For example: std::vector<int> c1; int v = 10; <--- I want to capture this variable std::for_each( c1.begin(), c1.end(), [v](int num) <--- This is fine... { std::vector<int> c2; std::for_each( c2.begin(), c2.end(), [v](int num) <--- error on this line, how do I recapture v? { // Do something }); });
std::for_each( c1.begin(), c1.end(), [&](int num) { std::vector<int> c2; int& v_ = v; std::for_each( c2.begin(), c2.end(), [&](int num) { v_ = num; } ); } ); Not especially clean, but it does work.
2,891,865
2,891,875
bind() fails with windows socket error 10038
I'm trying to write a simple program that will receive a string of max 20 characters and print that string to the screen. The code compiles, but I get a bind() failed: 10038. After looking up the error number on msdn (socket operation on nonsocket), I changed some code from int sock; to SOCKET sock which shouldn't make a difference, but one never knows. Here's the code: #include <iostream> #include <winsock2.h> #include <cstdlib> using namespace std; const int MAXPENDING = 5; const int MAX_LENGTH = 20; void DieWithError(char *errorMessage); int main(int argc, char **argv) { if(argc!=2){ cerr << "Usage: " << argv[0] << " <Port>" << endl; exit(1); } // start winsock2 library WSAData wsaData; if(WSAStartup(MAKEWORD(2,0), &wsaData)!=0){ cerr << "WSAStartup() failed" << endl; exit(1); } // create socket for incoming connections SOCKET servSock; if(servSock=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)==INVALID_SOCKET) DieWithError("socket() failed"); // construct local address structure struct sockaddr_in servAddr; memset(&servAddr, 0, sizeof(servAddr)); servAddr.sin_family = AF_INET; servAddr.sin_addr.s_addr = INADDR_ANY; servAddr.sin_port = htons(atoi(argv[1])); // bind to the local address int servAddrLen = sizeof(servAddr); if(bind(servSock, (SOCKADDR*)&servAddr, servAddrLen)==SOCKET_ERROR) DieWithError("bind() failed"); // mark the socket to listen for incoming connections if(listen(servSock, MAXPENDING)<0) DieWithError("listen() failed"); // accept incoming connections int clientSock; struct sockaddr_in clientAddr; char buffer[MAX_LENGTH]; int recvMsgSize; int clientAddrLen = sizeof(clientAddr); for(;;){ // wait for a client to connect if((clientSock=accept(servSock, (sockaddr*)&clientAddr, &clientAddrLen))<0) DieWithError("accept() failed"); // clientSock is connected to a client // BEGIN Handle client cout << "Handling client " << inet_ntoa(clientAddr.sin_addr) << endl; if((recvMsgSize = recv(clientSock, buffer, MAX_LENGTH, 0)) <0) DieWithError("recv() failed"); cout << "Word in the tubes: " << buffer << endl; closesocket(clientSock); // END Handle client } } void DieWithError(char *errorMessage) { fprintf(stderr, "%s: %d\n", errorMessage, WSAGetLastError()); exit(1); }
The problem is with servSock=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)==INVALID_SOCKET which does not associate as you think it does. Why would you even want to write something like that, what's wrong with SOCKET servSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(servSock == INVALID_SOCKET) DieWithError("socket() failed"); ?
2,891,926
3,328,170
Create thread is not accepting the member function
I am trying to create a class for network programming. This will create a general purpose socket with thread. But when I tried to crete the thread using createthread(). The third argument is producing errors. And from the net I came to know that I can't use the member functions as an argument to the createthread(). Is there any thing by which I can achieve this?
At lost I got it, the very fact is, in CreateThread if you pass the socket then there is no trouble. Because CreateThread is taking care of that socket. But if you pass as an object which is having that socket, then CreateThread is not taking care of the socket, and it is ends up in invalid socket in the new thread. The successed code below SOCKET s=socket(....); bind(s,...); listen(s,...); SOCKET temp=accept(s,(sockaddr *)&addrNew,&size); DWORD threadId; HANDLE thread=CreateThread(NULL,0,&MyThreadFunction,(LPVOID)(temp),0,&threadId);
2,891,966
2,892,158
What are the advantages of squashing assignment and error checking in one line?
This question is inspired by this question, which features the following code snippet. int s; if((s = foo()) == ERROR) print_error(); I find this style hard to read and prone to error (as the original question demonstrates -- it was prompted by missing parentheses around the assignment). I would instead write the following, which is actually shorter in terms of characters. int s = foo(); if(s == ERROR) print_error(); This is not the first time I've seen this idiom though, and I'm guessing there are reasons (perhaps historical) for it being so often used. What are those reasons?
When you are writing a loop, it is sometimes desirable to use the first form, as in this famous example from K&R: int c; while ((c = getchar()) != EOF) { /* stuff */ } There is no elegant "second-form" way of writing this without a repetition: int c = getchar(); while (c != EOF) { /* stuff */ c = getchar(); } Or: int c; for (c = getchar(); c != EOF; c = getchar()) { /* stuff */ } Now that the assignment to c is repeated, the code is more error-prone, because one has to keep both the statements in sync. So one has to be able to learn to read and write the first form easily. And given that, it seems logical to use the same form in if conditions as well. I tend to use the first form mostly because I find it easy to read—as someone else said, it couples the function call and the return value test much more closely.
2,892,087
2,892,133
If the address of a function can not be resolved during deduction, is it SFINAE or a compiler error?
In C++0x SFINAE rules have been simplified such that any invalid expression or type that occurs in the "immediate context" of deduction does not result in a compiler error but rather in deduction failure (SFINAE). My question is this: If I take the address of an overloaded function and it can not be resolved, is that failure in the immediate-context of deduction? (i.e is it a hard error or SFINAE if it can not be resolved)? Here is some sample code: struct X { // template<class T> T* foo(T,T); // lets not over-complicate things for now void foo(char); void foo(int); }; template<class U> struct S { template<int> struct size_map { typedef int type; }; // here is where we take the address of a possibly overloaded function template<class T> void f(T, typename size_map<sizeof(&U::foo)>::type* = 0); void f(...); }; int main() { S<X> s; // should this cause a compiler error because 'auto T = &X::foo' is invalid? s.f(3); } Gcc 4.5 states that this is a compiler error, and clang spits out an assertion violation. Here are some more related questions of interest: Does the FCD-C++0x clearly specify what should happen here? Are the compilers wrong in rejecting this code? Does the "immediate-context" of deduction need to be defined a little better? Thanks!
template<class T> void f(T, typename size_map<sizeof(&U::foo)>::type* = 0); This doesn't work, because U does not participate in deduction. While U is a dependent type, during deduction for f it's treated like a fixed type spelled with a nondependent name. You need to add it to the parameter list of f /* fortunately, default arguments are allowed for * function templates by C++0x */ template<class T, class U1 = U> void f(T, typename size_map<sizeof(&U1::foo)>::type* = 0); So in your case because U::foo does not depend on parameters of f itself, you receive an error while implicitly instantiating S<X> (try to comment out the call, and it should still fail). The FCD says at 14.7.1/1 The implicit instantiation of a class template specialization causes the implicit instantiation of the declarations, but not of the definitions or default arguments, of the class member functions, member classes, static data members and member templates; That is, if you implicitly instantiate S<X> the following function template declaration will be instantiated template<class T> void S<X>::f(T, typename size_map<sizeof(&X::foo)>::type* = 0); Analysis on that template declaration will then find that it can't resolve the reference to X::foo and error out. If you add U1, the template declaration will not yet try to resolve the reference to U1::foo (since U1 is a parameter of f), and will thus remain valid and SFINAE when f is tried to be called.
2,892,096
2,894,132
Serial: write() throttling?
I'm working on a project sending serial data to control animation of LED lights, which need to stay in sync with an animation engine. There seems to be a large serial write buffer (OSX (POSIX) + FTDI chipset usb serial device), so without manually throttling calls to write(), the software can get several seconds ahead of the lights. Currently I'm manually restricting the serial write speed to the baudrate (8N1 = 10 bytes serial frame per 8 bytes data, 19200 bps serial -> 1920 bytes per second max), but I am having a problem with the animation drifting out of sync with the lights over time - it starts fine, but after 10 minutes there's a noticeable (100ms+) lag between the animation and the lights. This is the code that's restricting the serial write speed (called once per animation frame, 'elapsed' is the duration of the current frame, 'baudrate' is the bps (19200)): void BufferedSerial::update( float elapsed ) { baud_timer += elapsed; if ( bytes_written > 1024 ) { // maintain baudrate float time_should_have_taken = (float(bytes_written)*10)/float(baudrate); float time_actually_took = baud_timer; // sleep if we have > 20ms lag between serial transmit and our write calls if ( time_should_have_taken-time_actually_took > 0.02f ) { float sleep_time = time_should_have_taken - time_actually_took; int sleep_time_us = sleep_time*1000.0f*1000.0f; //printf("BufferedSerial::update sleeping %i ms\n", sleep_time_us/1000 ); delayUs( sleep_time_us ); // subtract 128 bytes bytes_written -= 128; // subtract the time it should have taken to write 128 bytes baud_timer -= (float(128)*10)/float(baudrate); } } } Clearly there's something wrong, somewhere. A much better approach would be to be able to determine the number of bytes currently in the transmit queue, and try and keep that below a fixed threshold, but I can't figure out how to do this on an OSX (POSIX) system. Any advice appreciated.
If you want to slow your animation down to match the maximum speed that you can write to the LEDs, you can just use tcdrain(); something like this: while (1) { write(serial_fd, led_command); animate_frame(); tcdrain(serial_fd); }
2,892,189
2,892,378
Color space - RGB and YCbCr question
I am now trying to understand how JPEG encoding works and everything seems fine except the color transformation part. Before attempting to do a DCT in JPEG algorithm, the image is transformed into YCbCr color space. To me this essentially means that we just (comparing to initial RGB image) take a chunk of color information and dispose it while applying the RGB -> YCbCr transformation. So, our encoding steps look generally like RGB -> YCbCr -> DCT -> Huffman. The decoding means inversing this process. And my question is - why does the image (for example, created and exported to JPEG) remain the same in terms of color, although we have to make inverse YCbCr -> RGB transform. Where does the disposed part of color information comes from or how is it handled?
To me this essentially means that we just (comparing to initial RGB image) take a chunk of color information and dispose it while applying the RGB -> YCbCr transformation. No information gets disposed by the transformation itself. The transformation is reversible in a mathematical sense. E.g. if you convert a color to YCbCr and transform the result back to RGB you get the same color back. In a perfect world after all. In practice there is a loss of information. Assume that you start with three bytes in RGB. If you convert to YCbCr you get three values of which two, namely Cb and Cr don't fit into 8 bit anymore. Speaking technically the two representations RGB and YUV have a different gamut (http://en.wikipedia.org/wiki/Gamut) This information loss is fortunately rarely visible. Important side-node: This gamut thing is an unwanted side-effect and has nothing to do with the choice of using YCbCr at the first place. The point of using YCbCr is, that the data stored in Y is the most important. It is the brightness, or the gray-scale value. The data in Cb and Cr are the color information with brightness subtracted so to say. Now our eyes aren't that good at picking subtle differences in color, but they are sensitive to shades of intensity. To make use of this in jpeg only a low resolution image of Cb and Cr are stored and Y is stored at full resolution. There are different ways to do this with the most common one to leave out every other pixel from Cb and Cr in x and y. That reduces the space requirements by a factor of four for Cb and Cr. Where does the disposed part of color information comes from or how is it handled It does not magically come back. The information is lost forever. However, since the information wasn't that important to begin with we don't see much artifacts. In jpeg, the left out pixels of Cb and Cr panes are approximated by upscaling the Cb and Cr plane again. Some decoders just replicate the missing pixels by picking a neigbour, other do linear interpolation.
2,892,294
2,892,317
Creating many polygons with OpenGL is slow?
I want to draw many polygons to the screen but i'm quickly noticing that it slows down quickly. As a test I did this: for(int i = 0; i < 50; ++i) { glBegin( GL_POLYGON); glColor3f( 0.0f, 1, 0.0f ); glVertex2f( 500.0 + frameGL.GetCameraX(), 0.0f + frameGL.GetCameraY()); glColor3f( 0.0f, 1.0f, 0.0f ); glVertex2f( 900.0 + frameGL.GetCameraX(), 0.0f + frameGL.GetCameraY()); glColor3f( 0.0f, 0.0f, 0.5 ); glVertex2f(900.0 + frameGL.GetCameraX(), 500.0f + frameGL.GetCameraY() + (150)); glColor3f( 0.0f, 1.0f, 0.0f ); glVertex2f( 500 + frameGL.GetCameraX(), 500.0f + frameGL.GetCameraY()); glColor3f( 1.0f, 1.0f, 0.0f ); glVertex2f( 300 + frameGL.GetCameraX(), 200.0f + frameGL.GetCameraY()); glEnd(); } This is only 50 polygons and already it's gtting slow. I can't upload them directly to the card because my program will allow the user to reshape the verticies. My question is, how can I speed this up. I'm not using depth. I also know it's not my GetCamera() functions because if I create 500,000 polygons spread apart t's fine, it just has trouble showing them in the view. If a graphics card can support 500,000,000 on screen polygons per second, this should be easy right? Thanks
as already mentioned don't do glBegin and glEnd in the loop but outside for even better performance use vertex arrays for optimal performance use vertex buffer objects The solutions are ordered in how much speed gain you will get, and inversly how wide supported they are. That said, any modern graphics card supports all of those -- you just need to be careful when coding for embedded OpenGL systems. Contemporary games (the ones that achieve your cited 500kk limit) all use at least VBO's (if not Geometry Shaders, but that's even a step beyond). To effectively learn the techniques mentioned I honestly suggest taking them a step at a time -- e.g. first learning display lists, then vertex arrays, then VBO's, because in practice each one builds on top of the former. Immediate mode (characterized by using a GL command per object) is extremely slow, and even deprecated in the current GL standard -- a long theory short, it's because one of the most expensive graphics operation (apart from texture manipulation) are draw calls -- calls between the graphics card and the processor -- so in practice it's best to prepare all you can beforehand, and submit it to the GPU in one call (or as little as possible). Good luck!
2,892,303
2,892,364
how many color combinations in a 24 bit image
I am reading a book and I am not sure if its a mistake or I am misunderstanding the quote. It reads... Nowadays every PC you can buy has hardware that can render images with at least 16.7 million individual colors. Rather than have an array with thousands of color entries, the images instead contain explicit color values for each pixel. A 24-bit display, of course, uses 24 bits, or 3 bytes per pixel, for color information. This gives 1 byte, or 256 distinct values each, for red, green, and blue. This is generally called true color, because 256^3 (16.7 million) He says 1 byte is equal to 256 distinct values. 1 byte = 8 bits. 8^2 bits = 64 combinations of colors right ?? It's not adding up right to me. I know it might be something simple to understand, but I don't understand.
The combinations of 8 bits is not 82 (64) but 28 (256). This is because each of the 8 bits can have 2 distinct values. For 1 bit that would give you 2 (21) possibilities, for 2 bits 2*2 (22), for 3 bits 2*2*2 (23)... etc. 3 bytes = 24 bits => 224 = 16.7M possible combinations.
2,892,477
2,892,507
gcc optimization? bug? and its practial implication to project
My questions are divided into three parts Question 1 Consider the below code, #include <iostream> using namespace std; int main( int argc, char *argv[]) { const int v = 50; int i = 0X7FFFFFFF; cout<<(i + v)<<endl; if ( i + v < i ) { cout<<"Number is negative"<<endl; } else { cout<<"Number is positive"<<endl; } return 0; } No specific compiler optimisation options are used or the O's flag is used. It is basic compilation command g++ -o test main.cpp is used to form the executable. The seemingly very simple code, has odd behaviour in SUSE 64 bit OS, gcc version 4.1.2. The expected output is "Number is negative", instead only in SUSE 64 bit OS, the output would be "Number is positive". After some amount of analysis and doing a 'disass' of the code, I find that the compiler optimises in the below format - Since i is same on both sides of comparison, it cannot be changed in the same expression, remove 'i' from the equation. Now, the comparison leads to if ( v < 0 ), where v is a constant positive, So during compilation itself, the else part cout function address is added to the register. No cmp/jmp instructions can be found. I see that the behaviour is only in gcc 4.1.2 SUSE 10. When tried in AIX 5.1/5.3 and HP IA64, the result is as expected. Is the above optimisation valid? Or, is using the overflow mechanism for int not a valid use case? Question 2 Now when I change the conditional statement from if (i + v < i) to if ( (i + v) < i ) even then, the behaviour is same, this atleast I would personally disagree, since additional braces are provided, I expect the compiler to create a temporary built-in type variable and them compare, thus nullify the optimisation. Question 3 Suppose I have a huge code base, an I migrate my compiler version, such bug/optimisation can cause havoc in my system behaviour. Ofcourse from business perspective, it is very ineffective to test all lines of code again just because of compiler upgradation. I think for all practical purpose, these kinds of error are very difficult to catch (during upgradation) and invariably will be leaked to production site. Can anyone suggest any possible way to ensure to ensure that these kind of bug/optimization does not have any impact on my existing system/code base? PS : When the const for v is removed from the code, then optimization is not done by the compiler. I believe, it is perfectly fine to use overflow mechanism to find if the variable is from MAX - 50 value (in my case). Update(1) What would I want to achieve? variable i would be a counter (kind of syncID). If I do offline operation (50 operation) then during startup, I would like to reset my counter, For this I am checking the boundary value (to reset it) rather than adding it blindly. I am not sure if I am relying on the hardware implementation. I know that 0X7FFFFFFF is the max positive value. All I am doing is, by adding value to this, I am expecting the return value to be negative. I don't think this logic has anything to do with hardware implementation. Anyways, all thanks for your input. Update(2) Most of the inpit states that I am relying on the lower level behavior on overflow checking. I have one questions regarding the same, If that is the case, For an unsigned int how do I validate and reset the value during underflow or overflow? like if v=10, i=0X7FFFFFFE, I want reset i = 9. Similarly for underflow? I would not be able to do that unless I check for negativity of the number. So my claim is that int must return a negative number when a value is added to the +MAX_INT. Please let me know your inputs.
It's a known problem, and I don't think it's considered a bug in the compiler. When I compile with gcc 4.5 with -Wall -O2 it warns warning: assuming signed overflow does not occur when assuming that (X + c) < X is always false Although your code does overflow. You can pass the -fno-strict-overflow flag to turn that particular optimization off.
2,892,512
2,892,542
C++ Scoping and ambiguity in constructor overloads
I've tried the following code snippet in 3 different compilers (G++, clang++, CL.exe) and they all report to me that they cannot disambiguate the overloaded constructors. Now, I know how I could modify the call to the constructor to make it pick one or the other (either make explicit that the second argument is a unsigned literal value or explicitly cast it). However, I'm curious why the compiler would be attempting to choose between constructors in the first place given that one of the constructors is private and the call to the constructor is happening in the main function which should be outside the class's scope. Can anyone enlighten me? class Test { private: Test(unsigned int a, unsigned int *b) { } public: Test(unsigned int a, unsigned int b) { } }; int main() { Test t1 = Test(1,0); // compiler is confused }
In C++, accessibility to class members doesn't influence the other language semantics. Instead, any invalid access causes a program to be ill-formed. In other words, there is accessibility and visibility. The Standard has it straight It should be noted that it is access to members and base classes that is controlled, not their visibility. Names of members are still visible, and implicit conversions to base classes are still considered, when those members and base classes are inaccessible. The interpretation of a given construct is established without regard to access control. If the interpretation established makes use of inaccessible member names or base classes, the construct is ill-formed.
2,892,649
2,892,727
terminate called after throwing an instance of 'std::length_error'
this is my first post here. As i am newbie, the problem might be stupid. I was writing a piece of code while the following error message shown, terminate called after throwing an instance of 'std::length_error' what(): basic_string::_S_create /home/gcj/finals /home/gcj/quals where Aborted the following is the offending code especially Line 39 to Line 52. It is weired for me as this block of code is almost same as the Line64 to Line79. int main(){ std::vector<std::string> dirs, need; std::string tmp_str; std::ifstream fp_in("small.in"); std::ofstream fp_out("output"); std::string::iterator iter_substr_begin, iter_substr_end; std::string slash("/"); int T, N, M; fp_in>>T; for (int t = 0; t < T; t++){ std::cout<<" time "<< t << std::endl; fp_in >> N >> M; for (int n =0; n<N; n++){ fp_in>>tmp_str; dirs.push_back(tmp_str); tmp_str.clear(); } for (int m=0; m<M; m++){ fp_in>>tmp_str; need.push_back(tmp_str); tmp_str.clear(); } for (std::vector<std::string>::iterator iter = dirs.begin(); iter!=dirs.end(); iter++){ for (std::string::iterator iter_str = (*iter).begin()+1; iter_str<(*iter).end(); ++iter_str){ if ((*iter_str)=='/') { std::string tmp_str2((*iter).begin(), iter_str); if (find(dirs.begin(), dirs.end(), tmp_str2)==dirs.end()) { dirs.push_back(tmp_str2); } } } } for (std::vector<std::string>::iterator iter_tmp = dirs.begin(); iter_tmp!= dirs.end(); ++iter_tmp) std::cout<<*iter_tmp<<" "; dirs.clear(); std::cout<<std::endl; std::cout<<" need "<<std::endl; //processing the next for (std::vector<std::string>::iterator iter_tmp = need.begin(); iter_tmp!=need.end(); ++iter_tmp) std::cout<<*iter_tmp<<" "; std::cout<<" where "; for (std::vector<std::string>::iterator iter = need.begin(); iter!=need.end(); iter++){ for (std::string::iterator iter_str = (*iter).begin()+1; iter_str<(*iter).end(); ++iter_str){ if ((*iter_str)=='/') { std::string tmp_str2((*iter).begin(), iter_str); if (find(need.begin(), need.end(), tmp_str2)==need.end()) { need.push_back(tmp_str2); } } } } for (std::vector<std::string>::iterator iter_tmp = need.begin(); iter_tmp!= need.end(); ++iter_tmp) std::cout<<*iter_tmp<<" "; need.clear(); std::cout<<std::endl; //finish processing the next } for (std::vector<std::string>::iterator iter= dirs.begin(); iter!=dirs.end(); iter++) std::cout<<*iter<<" "; std::cout<<std::endl; for (std::vector<std::string>::iterator iter= need.begin(); iter!=need.end(); iter++) std::cout<<*iter<<" "; std::cout<<std::endl; fp_out.close(); } best regards, Mark
You are adding items to the dirs and need vectors while iterating over them. This is not allowed: if adding an item requires a reallocation, it will invalidate all existing iterators, and can cause various errors when you next access them.
2,892,673
2,892,711
textures and vertex arrays with OpenGL?
Basically what I'd like to do is make textured NGONS. I also want to use a tesselator (GLU) to make concave and multicontour objects. I was wondering how the texture comes into play though. I think that the tesselator will return verticies so I will add these to my array, that's fine. But my vertex array will contain more than one polygon object so then how can I tell it when to bind the texture like in immediate mode? Right now I feel stuck with one call to bind. How can this be done? Thanks
If you're going to use glDrawArrays or glDrawElements, you'll have to draw your vertices in pieces, one piece per texture. The same texture is used for the entire call. (These calls are like a potentially more efficient version of submitting the same data by hand within glBegin and glEnd, and you can't change texture inside a glBegin...glEnd block, either.) You could alternatively stick with glBegin and glEnd, and use glArrayElement to submit vertices whose attributes are taken out of the vertex arrays.
2,892,690
2,913,601
Mesh triangulation and simplification C++ library
I am looking for a C++ library to triangulate and simplify 3D mesh. My 3D meshes are potentially huge (around 3 millions vertices). It should ideally be open source. Any idea?
Here are some libraries I found: 1) CGAL ++ Does a lot of things; -- Licensing issues; 2) GTS ++ Open source and quite easy to use; -- Does less that CGAL anymore ideas?
2,892,781
3,030,420
Objective-C++ visibility question
I have linked a library with my program. It works fine. The only problem is that there visibility errors/warnings (thousands of them). They are all of the form: newlib::method() has different visibility (default) in newlib.a and (hidden) in AppDelegate.o It is always with AppDelegate.o. I have tried to set the visibility for both the library and the main app in several ways: the visibility checkmark in XCode, and -fvisibility. Non seem to have worked. Is there somethin special about AppDelegate.mm?
The XCode system for dealing with errors is not very bright. I had a function called Error() and XCode treated every warning about this function as an error.
2,892,832
2,893,140
Boost Thread Synchronization
I don't see synchronized output when i comment the the line wait(1) in thread(). can I make them run at the same time (one after another) without having to use 'wait(1)'? #include <boost/thread.hpp> #include <iostream> void wait(int seconds) { boost::this_thread::sleep(boost::posix_time::seconds(seconds)); } boost::mutex mutex; void thread() { for (int i = 0; i < 100; ++i) { wait(1); mutex.lock(); std::cout << "Thread " << boost::this_thread::get_id() << ": " << i << std::endl; mutex.unlock(); } } int main() { boost::thread t1(thread); boost::thread t2(thread); t1.join(); t2.join(); }
"at the same time (one after another)" is contradictory. With a call to sleep() they run at the same time. Without a call to sleep(), they run one after another. With only 100 lines to output, thread t1 completes before t2 has a change to begin execution. On my computer, I had to set your loop counter to 10000 before t1 ran long enough for t2 to launch while t1 was still executing: Thread 0x2305010: 0 Thread 0x2305010: 1 Thread 0x2305010: 2 ... Thread 0x2305010: 8730 Thread 0x2305010: 8731 Thread 0x23052a0: 0 Thread 0x23052a0: 1 ... Thread 0x23052a0: 146 Thread 0x23052a0: 147 Thread 0x2305010: 8732 Thread 0x2305010: 8733 etc Oh, and yes, if your goal was to make the two threads take turns executing, boost::condition_variable is the solution: boost::mutex mutex; boost::condition_variable cv; void thread() { for (int i = 0; i < 100; ++i) { boost::unique_lock<boost::mutex> lock(mutex); std::cout << "Thread " << boost::this_thread::get_id() << ": " << i << std::endl; cv.notify_one(); cv.wait(lock); } cv.notify_one(); }
2,892,855
2,892,887
What library to choose to build a user interface for a C++ software that uses SDL
I have a simulation software (C++) that runs on the command line. It is platform independent (currently compiling and running on Windows, MacOS X and Linux). When the simulation ends, I visualize the result with SDL; it is a very basic 2d view, mainly color squares next to each other. I would like to have a user interface on top of the simulation so that I can start and pause the simulation, and change the parameters on the fly. Something pretty simple I guess. Well, ideally I will also add a grapher somewhere to see the evolution over time of some parameters. Now, I am wondering what direction I should go. Should I try to use one of the UI libraries for SDL ? Or maybe wxwidget in conjunction with SDL ? Or simply wxwidget and get rid of SDL ? Do you have any experience with this ? Thanks in advance Barth PS: I tried to use AGAR, a SDL UI library. It seemed very promising but I couldn't get it working. Not even the helloworld.
Probably using wxWidgets without SDL would be the easiest way to go. SDL is a media layer -- it's supposed to allow cross-platform media application development. As you only need graphical display, you only need wxWidgets -- and it will be a lot easier too! You would benefit from SDL if: you'd need very fast blitting of very large amount of surfaces (we're talking the 60fps range here) you'd use RLE, color keying or other graphics operations you'd use other media (sound, advanced real-time input, etc) you'd need to run the software on embedded systems (handheld consoles, etc) If the answer to all 4 is "no", then you won't benefit from SDL, and using wx alone will be much easier.
2,892,928
2,897,215
Get version of installed Flash ActiveX in Win32/C++
Is this even possible? I'm embedding Flash inside an IE frame in my application and would like to check if Flash and what version of it is installed. The application needs to run without admin privileges. Bonus question: Can I also check if ActiveX controls are enabled in the IE settings?
The solution is to search for the CLSID of Flash ("{D27CDB6E-AE6D-11cf-96B8-444553540000}") in the registry under HKEY_CLASSES_ROOT\CLSID. There you can read \InprocServer32 which gives you the OCX. Then get the version via GetFileVersionInfo. This should work for any COM control.
2,893,101
2,893,123
How to rotate a N x N matrix by 90 degrees?
How to rotate a N x N matrix by 90 degrees. I want it to be inplace?
for(int i=0; i<n/2; i++) for(int j=0; j<(n+1)/2; j++) cyclic_roll(m[i][j], m[n-1-j][i], m[n-1-i][n-1-j], m[j][n-1-i]); void cyclic_roll(int &a, int &b, int &c, int &d) { int temp = a; a = b; b = c; c = d; d = temp; } Note I haven't tested this, just compoosed now on the spot. Please test before doing anything with it.
2,893,129
2,893,142
What does '**' mean in C?
What does it mean when an object has two asterisks at the beginning? **variable
It is pointer to pointer. For more details you can check: Pointer to pointer It can be good, for example, for dynamically allocating multidimensional arrays: Like: #include <stdlib.h> int **array; array = malloc(nrows * sizeof(int *)); if(array == NULL) { fprintf(stderr, "out of memory\n"); exit or return } for(i = 0; i < nrows; i++) { array[i] = malloc(ncolumns * sizeof(int)); if(array[i] == NULL) { fprintf(stderr, "out of memory\n"); exit or return } }
2,893,164
2,893,618
Texturing and Texture Mapping GLUTess Polygons?
How exactly does one provide texture coordinates and bind a texture for a GLUTess polygon? Thanks
I don't know If I understend you correctly. Texturing is described well in redbook. They use GLUT in the book, so you should find the answer in the examples. In short: call glTexCoord2f(u,v) before call to glVertex (if you do not use VBO), where u,v are texture coordinates. HTH EDIT: Sorry, now I understand the question. I have never used tesselators, but maybe I can help :-) Tesselators only find points where new vertices should be created. Standard glVertex is used to send them to the GPU. You can use your own function to draw vertex. If you register callback with gluTessCallback(tobj, GLU_TESS_VERTEX, (GLvoid (*) ()) &vertexCallback); then your function is called every time new vertex is created. You can also use gluTessCallback(tobj, GLU_TESS_COMBINE, (GLvoid (*) ()) &combineCallback); to add some information to the vertex - like normals, colors, tex coordinates. See redbook - chapter11 example 11-2 /* a different portion of init() */ gluTessCallback(tobj, GLU_TESS_VERTEX, (GLvoid (*) ()) &vertexCallback); gluTessCallback(tobj, GLU_TESS_BEGIN, (GLvoid (*) ()) &beginCallback); gluTessCallback(tobj, GLU_TESS_END, (GLvoid (*) ()) &endCallback); gluTessCallback(tobj, GLU_TESS_ERROR, (GLvoid (*) ()) &errorCallback); gluTessCallback(tobj, GLU_TESS_COMBINE, (GLvoid (*) ()) &combineCallback); /* new callback routines registered by these calls */ void vertexCallback(GLvoid *vertex) { const GLdouble *pointer; pointer = (GLdouble *) vertex; glColor3dv(pointer+3); glVertex3dv(vertex); } void combineCallback(GLdouble coords[3], GLdouble *vertex_data[4], GLfloat weight[4], GLdouble **dataOut ) { GLdouble *vertex; int i; vertex = (GLdouble *) malloc(6 * sizeof(GLdouble)); vertex[0] = coords[0]; vertex[1] = coords[1]; vertex[2] = coords[2]; for (i = 3; i < 7; i++) vertex[i] = weight[0] * vertex_data[0][i] + weight[1] * vertex_data[1][i] + weight[2] * vertex_data[2][i] + weight[3] * vertex_data[3][i]; *dataOut = vertex; } It should be sufficient to bind texture as usually - do it before drawing with tesselators. HTH
2,893,220
2,894,853
Organization of linking to external libraries in C++
In a cross-platform (Windows, FreeBSD) C++ project I'm working on, I am making use of two external libraries, Protocol Buffers and ZeroMQ. In both projects, I am tracking the latest development branch, so these libraries are recompiled / replaced often. For a development scenario, where is the best place to keep libprotobuf.{a,lib} and zeromq.{so,dll}? Should I have my build script copy them from their respective project directories into my local project's directory (say MyProjectRoot/lib or MyProjectRoot/bin) before I build my project? This seems preferable to tossing things into /usr/local/lib, as I wouldn't want to replace a system-wide stable version with the latest experimental one. Cmake warns me whenever I specify a relative path for linking, so I would suspect copying is a better solution then relative linking? Is this the best approach? Thanks for your help!
I would suggest you don't copy files around in the source tree, and definitely not into the system folder, instead go for a defined target location - $BUILD_TARGET/bin - final binary destination (.exe/.so/.dll etc) $BUILD_TARGET/obj - object file destination (.obj etc) $BUILD_TARGET/lib - static library destination (.lib etc) You can further develop this using optimization/debug targets - DEBUG $BUILD_TARGET/binD - final binary destination (.exe/.so/.dll etc) $BUILD_TARGET/objD - object file destination (.obj etc) $BUILD_TARGET/libD - static library destination (.lib etc) RELEASE (OPTIMIZED) $BUILD_TARGET/binO - final binary destination (.exe/.so/.dll etc) $BUILD_TARGET/objO - object file destination (.obj etc) $BUILD_TARGET/libO - static library destination (.lib etc) The possibilities are endless, x86/x64 etc.
2,893,365
2,893,375
Libraries for visualizing graphs in real-time using C++
Are there any good C++ libraries that can be used to visualize a graph of objects that have been instantiated and have random connections to each other? I would also need it to be able to be updated in real-time so that the graph was constantly updated.
If you use the Boost Graph Library then it supports the graphviz dot language. Otherwise it shouldn't be hard to write the code on your own.
2,893,713
2,893,798
Pthread Queue System
I'm working on my assignment on pthreads. I'm new and never touched on pthreads before. Is there any sample codes or resources out there that anyone of you have, that might aid me in my assignment? Here are my assignment details. A pthread program about queue system: Write a C/C++ Pthread program for a Dental clinic’s queuing system that declares an array of integers of size N, where N is the maximum number of queue for the day. The pthread program uses two threads. Whenever there is a new dental appointment, the first thread (the creator) puts the queue numbers in the array, one after the other. The second thread (the remover) removes the queue numbers from the array whenever the dentist has seen the patient. This is done in a FIFO fashion (First In First Out). The algorithm of the creator is as follows: • If the array is not full then put a new number in it (the numbers start at 1 and are incremented by one each time, so the creator create queue number 1, 2, 3 etc.) • sleep for 1 to 10 seconds, randomly • repeat The algorithm of the remover is as follows: • If the array is not empty then remove its smallest queue number. • sleep for 1 to 10 seconds, randomly • repeat You should use mutex locks to protect things that must be protected. Each thread should print on the screen what it is doing (eg: "number 13 is added into the queue", "number 7 is removed from the queue", etc.). The program should run forever. Any help will be appreciated. Thanks.
For generally starting out with pthreads, this is a good website with possibly more info than you need (but I like detail). It runs through a lot of the basics for pthreads and more. If you prefer a dead-tree tutorial, this book is pretty good and gives you a good grounding in most of the features of the Linux API, or the core libraries, if you want to call it that. This stackoverflow question deals with mutexes vs semaphores pretty concisely. Finally, I like this site for its converage of Linux Threading and Synchronisation. Hopefully these give you some reading material. Work out how you handle threads, then how you synchronise them, then attack your problem.
2,893,791
2,983,636
C++: Can virtual inheritance be detected at compile time?
I would like to determine at compile time if a pointer to Derived can be cast from a pointer to Base without dynamic_cast<>. Is this possible using templates and metaprogramming? This isn't exactly the same problem as determining if Base is a virtual base class of Derived, because Base could be the super class of a virtual base class of Derived. Thanks, Tim Update: I felt good about this method: #include <iostream> using namespace std; class Foo { }; class Bar : public Foo { }; class Baz : public virtual Foo { }; class Autre : public virtual Bar { }; typedef char Small; class Big { char dummy[2]; }; template<typename B, typename D> struct is_static_castable { const B* foo; char bar[1]; static Small test(char(*)[sizeof(static_cast<const D*>(foo)) == sizeof(const D*)]); static Big test(...); enum { value = (sizeof(test(&bar)) == sizeof(Small)) }; }; int main() { cout << "Foo -> Bar: " << is_static_castable<Foo, Bar>::value << "\n"; cout << "Foo -> Baz: " << is_static_castable<Foo, Baz>::value << "\n"; cout << "Foo -> Autre: " << is_static_castable<Foo, Autre>::value << "\n"; } But it doesn't work with gcc: multi-fun.cpp: In instantiation of ‘is_static_castable<Foo, Baz>’: multi-fun.cpp:38: instantiated from here multi-fun.cpp:29: error: cannot convert from base ‘Foo’ to derived type ‘Baz’ via virtual base ‘Foo’ multi-fun.cpp:29: error: array bound is not an integer constant multi-fun.cpp: In instantiation of ‘is_static_castable<Foo, Autre>’: multi-fun.cpp:39: instantiated from here multi-fun.cpp:29: error: cannot convert from base ‘Foo’ to derived type ‘Autre’ via virtual base ‘Bar’ multi-fun.cpp:29: error: array bound is not an integer constant Am I confused about what can be done with the sizeof() trick?
I had the same problem, once. Unfortunately, I'm not quite sure about the virtual-problem. But: Boost has a class named is_base_of (see here) which would enable you to do smth. like the following BOOST_STATIC_ASSERT((boost::is_base_of<Foo, Bar>::value)); Furthermore, there's a class is_virtual_base_of in Boost's type_traits, maybe that's what you're looking for.
2,894,006
2,894,011
How to assign a string value to a string variable in C++
Shouldn't this work? string s; s = "some string";
Yes! It's default constructing a string, then assigning it from a const char*. (Why did you post this question?... did you at least try it?)
2,894,083
2,894,102
Difference dynamic static 2d array c++
Im using opensource library called wxFreeChart to draw some XY charts. In example there is code which uses static array as a serie : double data1[][2] = { { 10, 20, }, { 13, 16, }, { 7, 30, }, { 15, 34, }, { 25, 4, }, }; dataset->AddSerie((double *) data1, WXSIZEOF(dynamicArray)); WXSIZEOF ismacro defined like: sizeof(array)/sizeof(array[0]) In this case everything works great but in my program Im using dynamic arrays (according to users input). I made a test and wrotecode like below: double **dynamicArray = NULL; dynamicArray = new double *[5] ; for( int i = 0 ; i < 5 ; i++ ) dynamicArray[i] = new double[2]; dynamicArray [0][0] = 10; dynamicArray [0][1] = 20; dynamicArray [1][0] = 13; dynamicArray [1][1] = 16; dynamicArray [2][0] = 7; dynamicArray [2][1] = 30; dynamicArray [3][0] = 15; dynamicArray [3][1] = 34; dynamicArray [4][0] = 25; dynamicArray [4][1] = 4; dataset->AddSerie((double *) *dynamicArray, WXSIZEOF(dynamicArray)); But it doesnt work correctly. I mean point arent drawn. I wonder if there is any possibility that I can "cheat" that method and give it dynamic array in way it understands it and will read data from correct place thanks for help
If You define an array like double myArr[5][2]; All cells occupy a continuous chunk of memory and I'm pretty sure dataset->AddSerie relies on that. You can't guarantee that if you allocate memory in chunks, using consecutive calls to new. My proposition is to write a simple class that allocates a continuous chunk of memory for storage and uses operator() to access that memory as a two dimensional array using 2 indices. Internally You can use a vector<double> to manage the storage, and You can pass the address of the first element of that vector to dataset->AddSerie Please check the code in this C++ FAQ example and try to understand it. The matrix example uses new[] and delete[]. You should use a vector instead, and the type double instead of Fred Where in the example, there is a private section like this class Matrix { public: ... private: unsigned nrows_, ncols_; Fred* data_; }; (The example shows a matrix of Freds) You should use a vector<double> class Matrix { public: ... private: unsigned nrows_, ncols_; vector<double> data_; }; That will make the code much simpler. You don't even need a destructor, because the vector manages the memory.
2,894,191
2,895,106
How can I improve my real-time behavior in multi-threaded app using pthreads and condition variables?
I have a multi-threaded application that is using pthreads. I have a mutex() lock and condition variables(). There are two threads, one thread is producing data for the second thread, a worker, which is trying to process the produced data in a real time fashion such that one chuck is processed as close to the elapsing of a fixed time period as possible. This works pretty well, however, occasionally when the producer thread releases the condition upon which the worker is waiting, a delay of up to almost a whole second is seen before the worker thread gets control and executes again. I know this because right before the producer releases the condition upon which the worker is waiting, it does a chuck of processing for the worker if it is time to process another chuck, then immediately upon receiving the condition in the worker thread, it also does a chuck of processing if it is time to process another chuck. In this later case, I am seeing that I am late processing the chuck many times. I'd like to eliminate this lost efficiency and do what I can to keep the chucks ticking away as close to possible to the desired frequency. Is there anything I can do to reduce the delay between the release condition from the producer and the detection that that condition is released such that the worker resumes processing? For example, would it help for the producer to call something to force itself to be context switched out? Bottom line is the worker has to wait each time it asks the producer to create work for itself so that the producer can muck with the worker's data structures before telling the worker it is ready to run in parallel again. This period of exclusive access by the producer is meant to be short, but during this period, I am also checking for real-time work to be done by the producer on behalf of the worker while the producer has exclusive access. Somehow my hand off back to running in parallel again results in significant delay occasionally that I would like to avoid. Please suggest how this might be best accomplished.
I could suggest the following pattern. Generally the same technique could be used, e.g. when prebuffering frames in some real-time renderers or something like that. First, it's obvious that approach that you describe in your message would only be effective if both of your threads are loaded equally (or almost equally) all the time. If not, multi-threading would actually benefit in your situation. Now, let's think about a thread pattern that would be optimal for your problem. Assume we have a yielding and a processing thread. First of them prepares chunks of data to process, the second makes processing and stores the processing result somewhere (not actually important). The effective way to make these threads work together is the proper yielding mechanism. Your yielding thread should simply add data to some shared buffer and shouldn't actually care about what would happen with that data. And, well, your buffer could be implemented as a simple FIFO queue. This means that your yielding thread should prepare data to process and make a PUSH call to your queue: X = PREPARE_DATA() BUFFER.LOCK() BUFFER.PUSH(X) BUFFER.UNLOCK() Now, the processing thread. It's behaviour should be described this way (you should probably add some artificial delay like SLEEP(X) between calls to EMPTY) IF !EMPTY(BUFFER) PROCESS(BUFFER.TOP) The important moment here is what should your processing thread do with processed data. The obvious approach means making a POP call after the data is processed, but you will probably want to come with some better idea. Anyway, in my variant this would look like // After data is processed BUFFER.LOCK() BUFFER.POP() BUFFER.UNLOCK() Note that locking operations in yielding and processing threads shouldn't actually impact your performance because they are only called once per chunk of data. Now, the interesting part. As I wrote at the beginning, this approach would only be effective if threads act somewhat the same in terms of CPU / Resource usage. There is a way to make these threading solution effective even if this condition is not constantly true and matters on some other runtime conditions. This way means creating another thread that is called controller thread. This thread would merely compare the time that each thread uses to process one chunk of data and balance the thread priorities accordingly. Actually, we don't have to "compare the time", the controller thread could simply work the way like: IF BUFFER.SIZE() > T DECREASE_PRIORITY(YIELDING_THREAD) INCREASE_PRIORITY(PROCESSING_THREAD) Of course, you could implement some better heuristics here but the approach with controller thread should be clear.
2,894,229
2,894,236
Running a shellscript from a C++ application and check if it succeeds
I am creating an interpreter for my extension to HQ9+, which has the following extra command called V: V: Interpretes the code as Lua, Brainfuck, INTERCAL, Ruby, ShellScript, Perl, Python, PHP in that order, and if even one error has occoured, run the HQ9+-ABC code again most of them have libraries, BF and INTERCAL can be interpreted without a library, but the problem lies in ShellScript. How can I run a shellscript from my C++ application ( =the HQ9+-ABC interpreter) and when it's done, get the error code (0 = succeded, all others = failed)? So something like this: system(".tempshellscript738319939474"); if(errcode != 0) { (rerun code); } can anyone help me? Thanks
From man system(3): RETURN VALUE The value returned is -1 on error (e.g. fork failed), and the return status of the command otherwise. This latter return status is in the format specified in wait(2). Thus, the exit code of the command will be WEXITSTATUS(status). In case /bin/sh could not be executed, the exit status will be that of a command that does exit(127).
2,894,306
2,895,253
GLTessellator crashing
I'v followed a tutorial to get the GLU tesselator working. It works except the interpolation for colors of new points causes a crash after creating a random polygon(error reading from memory...) This is my callback where it crashes: void CALLBACK combineCallback(GLdouble coords[3], GLdouble *vertex_data[4], GLfloat weight[4], GLdouble **dataOut) { GLdouble *vertex; int i; vertex = (GLdouble *) malloc(6 * sizeof(GLdouble)); vertex[0] = coords[0]; vertex[1] = coords[1]; vertex[2] = coords[2]; //crashes here **for (int i = 3; i < 6; i++) { vertex[i] = weight[0] * vertex_data[0][i] + weight[1] * vertex_data[1][i] + weight[2] * vertex_data[2][i] + weight[3] * vertex_data[3][i]; }** //crashes here *dataOut = vertex; } I looked at memory when it crashes but can't put my finger on exactly what triggers it. I followed this tutorial: http://www.flipcode.com/archives/Polygon_Tessellation_In_OpenGL.shtml Thanks
My guess is that vertex_data is wrong. It is the same pointer that you pass to gluTessVertex function. What does that pointer point to?
2,894,391
2,894,632
Best way to get individual digits from int for radix sort in C/C++
What is the best way to get individual digits from an int with n number of digits for use in a radix sort algorithm? I'm wondering if there is a particularly good way to do it in C/C++, if not what is the general best solution? edit: just to clarify, i was looking for a solution other than converting it to a string and treating it like an array of digits.
Use digits of size 2^k. To extract the nth digit: #define BASE (2<<k) #define MASK (BASE-1) inline unsigned get_digit(unsigned word, int n) { return (word >> (n*k)) & MASK; } Using the shift and mask (enabled by base being a power of 2) avoids expensive integer-divide instructions. After that, choosing the best base is an experimental question (time/space tradeoff for your particular hardware). Probably k==3 (base 8) works well and limits the number of buckets, but k==4 (base 16) looks more attractive because it divides the word size. However, there is really nothing wrong with a base that does not divide the word size, and you might find that base 32 or base 64 perform better. It's an experimental question and may likely differ by hardware, according to how the cache behaves and how many elements there are in your array. Final note: if you are sorting signed integers life is a much bigger pain, because you want to treat the most significant bit as signed. I recommend treating everything as unsigned, and then if you really need signed, in the last step of your radix sort you will swap the buckets, so that buckets with a most significant 1 come before a most significant 0. This problem is definitely easier if k divides the word size.
2,894,429
2,894,450
Will a destructor destroy a static member?
Say I have: class A { A() {} ~A() {} }; class B { public: B() {} ~B() {} private: static A mA; }; B* pB = new B; delete pB; When I call delete pB, B's destructor will be called. Will this then call the destructor for static member A?
The keyword static means that the variable is independent of instances. That's why you can access static variables and methods without instantiating an object from the class in the first place. That's why destroying an instance will not affect any static variables.
2,894,595
2,898,140
Source-to-source compiler framework wanted
I used to use OpenC++ (http://opencxx.sourceforge.net/opencxx/html/overview.html) to perform code generation like: Source: class MyKeyword A { public: void myMethod(inarg double x, inarg const std::vector<int>& y, outarg double& z); }; Generated: class A { public: void myMethod(const string& x, double& y); // generated method below: void _myMehtod(const string& serializedInput, string& serializedOutput) { double x; std::vector<int> y; // deserialized x and y from serializedInput double z; myMethod(x, y, z); } }; This kind of code generation directly matches the use case in the tutorial of OpenC++ (http://www.csg.is.titech.ac.jp/~chiba/opencxx/tutorial.pdf) by writing a meta-level program for handling "MyKeyword", "inarg" and "outarg" and performing the code generation. However, OpenC++ is sort of out-of-date and inactive now, and my code generator can only work on g++ 3.2 and it triggers error on parsing header files of g++ of higher version. I have looked at VivaCore, but it does not provide the infra-structure for compiling meta-level program. I'm also looking at LLVM, but I cannot find documentation that tutor me on working out my source-to-source compilation usage. I'm also aware of the ROSE compiler framework, but I'm not sure whether it suits my usage, and whether its proprietary C++ front-end binary can be used in a commercial product, and whether a Windows version is available. Any comments and pointers to specific tutorial/paper/documentation are much appreciated.
I do not know of any ready-to-use solution, but you could build your own with a relatively little effort. One possible option is Elsa C++ parser, a bit out of date, but easy to use and quite extendible. Another option is to tamper with XML ASTs produced by Clang++. I used both approaches in different scenarios.
2,894,804
2,895,304
Handling lot of items in std::stack
Can C++ std::stack handle more than 10k int items? And how about its performance?
The performance depends on the underlying container used. As already mentioned, stack is an adapter, the underlying container can be deque (the default), or vector, or list (all in std namespace). Following is an example of performance comparison. As the type to be stored is not clearly mentioned in the question, I am assuming it to be unsigned int. Feel free to change it per your requirements. The example constructs a stack of 100K items. Contents of stack.cpp #include <stack> #include <vector> #include <list> #include <deque> #include <assert.h> typedef unsigned int Type; #ifdef USE_VECTOR typedef std::stack< Type, std::vector< Type > > StackType; #elif USE_LIST typedef std::stack< Type, std::list< Type > > StackType; #else typedef std::stack< Type, std::deque< Type > > StackType; #endif int main() { StackType mystack; for( unsigned int i = 0; i < 100 * 1024; ++i ) { mystack.push( i ); } assert( mystack.size() == 100 * 1024 ); return 0; } Execution comparison: $ g++ -DUSE_VECTOR stack.cpp -o stack; time ./stack real 0m0.023s user 0m0.030s sys 0m0.031s $ g++ -DUSE_LIST stack.cpp -o stack; time ./stack real 0m0.144s user 0m0.186s sys 0m0.030s $ g++ stack.cpp -o stack; time ./stack real 0m0.024s user 0m0.030s sys 0m0.015s asaha@nedata8 ~/code $ The above numbers are result of single run. To achieve statistically significant numbers run each variation large number of times, and observe the mean and standard deviation. Apparently, deque and vector results in similar performance, whereas list is worse.
2,895,313
2,895,330
What is the cost of a #define?
To define constants, what is the more common and correct way? What is the cost, in terms of compilation, linking, etc., of defining constants with #define? It is another way less expensive?
The best way to define any const is to write const int m = 7; const float pi = 3.1415926f; const char x = 'F'; Using #define is a bad c++ style. It is impossible to hide #define in namespace scope. Compare #define pi 3.1415926 with namespace myscope { const float pi = 3.1415926f; } Second way is obviously better.