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,712,076
2,712,125
How to use an iterator?
I'm trying to calculate the distance between two points. The two points I stored in a vector in C++: (0,0) and (1,1). I'm supposed to get results as 0 1.4 1.4 0 But the actual result that I got is 0 1 -1 0 I think there's something wrong with the way I use iterator in vector. How can I fix this problem? I posted the code below. typedef struct point { float x; float y; } point; float distance(point *p1, point *p2) { return sqrt((p1->x - p2->x)*(p1->x - p2->x) + (p1->y - p2->y)*(p1->y - p2->y)); } int main() { vector <point> po; point p1; p1.x = 0; p1.y = 0; point p2; p2.x = 1; p2.y = 1; po.push_back(p1); po.push_back(p2); vector <point>::iterator ii; vector <point>::iterator jj; for (ii = po.begin(); ii != po.end(); ii++) { for (jj = po.begin(); jj != po.end(); jj++) { cout << distance(ii,jj) << " "; } } return 0; }
That your code compiles at all is probably because you have a using namespace std somewhere. (Otherwise vector would have to be std::vector.) That's something I would advise against and you have just provided a good case why: By accident, your call picks up std::distance(), which takes two iterators and calculates the distance between them. Remove the using directive and prefix all standard library types with std:: and the compiler will tell you that you tried to pass a vector <point>::iterator where a point* was required. To get a pointer to an object an iterator points to, you'd have to dereference the iterator - which gives a reference to the object - and take the address of the result: &*ii. (Note that a pointer would perfectly fulfill all requirements for a std::vector iterator and some earlier implementations of the standard library indeed used pointers for that, which allowed you to treat std::vector iterators as pointers. But modern implementations use a special iterator class for that. I suppose the reason is that using a class allows overloading functions for pointers and iterators. Also, using pointers as std::vector iterators encourages mixing pointers and iterators, which will prevent the code to compile when you change your container.) But rather than doing this, I suggest you change your function so that it takes references instead (see this answer for why that's a good idea anyway.) : float distance(const point& p1, const point& p2) { return sqrt((p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y)); } Note that the points are taken by const references. This indicates to the caller that the function won't change the points it is passed. Then you can call it like this: distance(*ii,*jj). On a side note, this typedef struct point { float x; float y; } point; is a C-ism unnecessary in C++. Just spell it struct point { float x; float y; }; That would make problems if this struct definition ever was to parse from a C compiler (the code would have to refer to struct point then, not simply point), but I guess std::vector and the like would be far more of a challenge to a C compiler anyway.
2,712,377
2,712,494
How to 'hide' spurious "declared but never used" warnings?
I'm using the Borland (AKA "Embarcodegearland") C++Builder 2007 compiler which has a minor bug that certain static const items from system header files can cause spurious "xyzzy is declared but never used" warnings. I'm trying to get my code 100% warning free, so want a way of masking these particular warnings (note - but not by simply turning off the warning!) Also, I can't modify the header files. I need a way of 'faking' the use of the items, preferably without even knowing their type. As an example, adding this function to my .cpp modules fixes warnings for these four items, but it seems a bit 'ad-hoc'. Is there a better and preferably self-documenting way of doing this? static int fakeUse() { return OneHour + OneMinute + OneSecond + OneMillisecond; } EDIT: Alex suggested something like this: #pragma option push #pragma warn -8080 #include "dateutils.hpp" #pragma option pop ...which sadly doesn't work because the warning status isn't managed cleverly by the compiler, so messages are still shown. EDIT #2: AshleysBrain has a good suggestion. I've implemented it by building a "dateutils_fix.hpp" header file like this: #ifndef DATEUTILS_FIXH #define DATEUTILS_FIXH #include <dateutils.hpp> static void FIX_DATEUTIL_WARNINGS() { UNREFERENCED(OneHour); UNREFERENCED(OneMinute); UNREFERENCED(OneSecond); UNREFERENCED(OneMillisecond); } #endif ... and then #including this header instead of dateutils.hpp in my own code.
A common way to reference variables is something like this: #define UNREFERENCED(x) ((void)x) // ... void MyFunc() { const int x = 5; // never used for whatever reason UNREFERENCED(x); // stops compiler warning } The 'cast to void' effectively means 'do nothing with this expression' so should be equivalent to a no-op. It also counts as a reference to the variable though, so the warning is silenced. You need to place it in a function code though, so maybe a class constructor or startup method will do for you. I don't have C++ Builder to try it on, but this works for other compilers.
2,712,398
2,712,503
Boost binding a function taking a reference
I am having problems compiling the following snippet int temp; vector<int> origins; vector<string> originTokens = OTUtils::tokenize(buffer, ","); // buffer is a char[] array // original loop BOOST_FOREACH(string s, originTokens) { from_string(temp, s); origins.push_back(temp); } // I'd like to use this to replace the above loop std::transform(originTokens.begin(), originTokens.end(), origins.begin(), boost::bind<int>(&FromString<int>, boost::ref(temp), _1)); where the function in question is // the third parameter should be one of std::hex, std::dec or std::oct template <class T> bool FromString(T& t, const std::string& s, std::ios_base& (*f)(std::ios_base&) = std::dec) { std::istringstream iss(s); return !(iss >> f >> t).fail(); } the error I get is 1>Compiling with Intel(R) C++ 11.0.074 [IA-32]... (Intel C++ Environment) 1>C:\projects\svn\bdk\Source\deps\boost_1_42_0\boost/bind/bind.hpp(303): internal error: assertion failed: copy_default_arg_expr: rout NULL, no error (shared/edgcpfe/il.c, line 13919) 1> 1> return unwrapper<F>::unwrap(f, 0)(a[base_type::a1_], a[base_type::a2_]); 1> ^ 1> 1>icl: error #10298: problem during post processing of parallel object compilation Google is being unusually unhelpful so I hope that some one here can provide some insights. UPDATE: Question is answered by @gf's solution, but interestingly the original function wasn't quite correct as it stored the result of the conversion operation (failed/not failed) rather than the converted value itself. I changed the signature return the converted value directly and the compiler was able to infer the type of the binding correctly. // new signature T FromString(const std::string& s, std::ios_base& (*f)(std::ios_base&) = std::dec); // revised calling syntax - note that bind<int> is not required. transform(originTokens.begin(), originTokens.end(), origins.begin(), bind(&FromString<int>, _1, std::dec));
FromString() takes 3 arguments and default arguments are not part of a functions type. So the bind expression should probably be something like: boost::bind<int>(&FromString<int>, boost::ref(temp), _1, std::dec);
2,712,499
2,713,674
Is it possible to create your own custom locale
Since Windows doesnt have a C++ locale with UTF8 support by default, i would like to construct a custom locale object which supports UTF8 (by creating it with a custom ctype facet). How can i construct a locale object with a my own ctype implementation (i only found functions to construct a locale using an already existing locale as base..) If C++ does not support construction of locales with a custom ctype facet at all, why is that so ?
It's possible to create custom facets by inheriting from std::locale::facet. Locales can use those custom facets as in following code: class custom_facet : public std::locale::facet { public: static std::locale::id id; custom_facet(int); int custom_value() const; }; std::locale custom_locale ( std::locale(), new custom_facet() ); int s = std::use_facet<custom_facet>(custom_locale).custom_value();
2,712,560
2,712,575
Trivial Q about redefinition
Why this isn't allowed: int a = 0; int a = 0; but this is: for (int i = 0; i < 2; ++i) { int a = 0; } As far as I know code inside for loop will be executed twice whitout actually going out of its scope, so it should also be an error to define a twice. Looking forward to your answers Thanks.
There is a single definition within the for loop. The variable gets created, used, then destroyed at the closing curly brace and recreated in the next loop iteration. There is a single variable defined. This is somehow similar to a variable defined in a function. The function can be called many times, but the variable is one. In fact with functions, the function can be called recursively and there will be more than one variable alive, but for each execution of the function there is a single variable defined. EDIT: Note, as @xtofl correctly points out, that the lifetime of i is the entire for loop, while the lifetime of a is the block in the curly braces: a single iteration of the for loop.
2,712,894
2,712,947
How to insert into std::map
In code below: map<string,vector<int>> create(ifstream& in, const vector<string>& vec) { /*holds string and line numbers into which each string appears*/ typedef map<string,vector<int>> myMap; typedef vector<string>::const_iterator const_iter; myMap result; string tmp; unsigned int lineCounter = 0; while(std::getline(in,tmp)) { const_iter beg = vec.begin(); const_iter end = vec.end(); while (beg < end) { if ( tmp.find(*beg) != string::npos) { result[*beg].push_back(lineCounter);//THIS IS THE LINE I'M ASKING FOR } ++beg; } ++lineCounter; } return result; } How should I do it (check line commented in code) if I want to use insert method of map instead of using operator[]? Thank you.
Seriously, I would not do it. You are only going to complicate your code unnecessarily. You would need a call to the insert to generate the new element in the map and then modify it. Just for the sake of it (avoiding the double lookup, but building an unnecessary empty vector): result.insert( std::make_pair( *beg, std::vector<int>() ) ) .first->second.push_back( lineCounter ); EDIT: Real equivalent (functionality and performance): std::map<std::string,std::vector<int> >::iterator it = result.upper_bound( *beg ); if ( it->first != *beg ) { it = result.insert( it, std::make_pair( *beg, std::vector<int>() ) ).first; } it->second.push_back( lineCounter );
2,713,043
2,713,073
Access violation of member of pointer object
So I am coding this client/server program. This code is from the client side. The client has an instance of an object mpqs_sieve *instance_; The reason I make it as a pointer is, that mpqs_sieve only has a constructor that takes 3 arguments, and I want to instantiate it at a later point in time. The client first gets some data from the server, and uses this to instantiate instance_. After this, it will request some more data, and upon receiving this (these are three coefficients for a quadratic polynomial), it should set these in the instance_ object. However upon calling a member function of instance_, I get an access violation on one of the members of instance_ within that function call. I posted my code here: on pastebin, and I get the error on line 100. The call comes from line 71, and before that line 21. Here's an excerpt: class client_protocol { public: static std::string parse_message( network_message& msg, mpqs_sieve *instance_) { // ... return set_mpqs_data(m.substr(i+1), instance_); } private: static std::string set_mpqs_data( std::string data, mpqs_sieve *instance_) { instance_ = new mpqs_sieve(n, M, FB_count); // ... } }; Any ideas to solve this?
You are passing a copy of the instance_ pointer to the function, not a reference to the variable. When you assign to instance_, you're modifying a local variable, not the member variable with the same name. Change the function parameter to mpqs_sieve *&instance_.
2,713,160
2,713,282
Ambiguous access to base class template member function
In Visual Studio 2008, the compiler cannot resolve the call to SetCustomer in _tmain below and make it unambiguous: template <typename TConsumer> struct Producer { void SetConsumer(TConsumer* consumer) { consumer_ = consumer; } TConsumer* consumer_; }; struct AppleConsumer { }; struct MeatConsumer { }; struct ShillyShallyProducer : public Producer<AppleConsumer>, public Producer<MeatConsumer> { }; int _tmain(int argc, _TCHAR* argv[]) { ShillyShallyProducer producer; AppleConsumer consumer; producer.SetConsumer(&consumer); // <--- Ambiguous call!! return 0; } This is the compilation error: // error C2385: ambiguous access of 'SetConsumer' // could be the 'SetConsumer' in base 'Producer<AppleConsumer>' // or could be the 'SetConsumer' in base 'Producer<MeatConsumer>' I thought the template argument lookup mechanism would be smart enough to deduce the correct base Producer. Why isn't it? I could get around this by changing Producer to template <typename TConsumer> struct Producer { template <typename TConsumer2> void SetConsumer(TConsumer2* consumer) { consumer_ = consumer; } TConsumer* consumer_; }; and call SetConsumer as producer.SetConsumer<AppleConsumer>(&consumer); // Unambiguous call!! but it would be nicer if I didn't have to...
I thought the template argument lookup mechanism would be smart enough to deduce the correct base Producer. This hasn't to do with templates, it comes from using multiple base classes - the name lookup is already ambiguous and overload resolution only takes place after that. A simplified example would be the following: struct A { void f() {} }; struct B { void f(int) {} }; struct C : A, B {}; C c; c.f(1); // ambiguous Workarounds are explicitly qualifying the call or to introduce the functions into the derived classes scope: struct ShillyShallyProducer : public Producer<AppleConsumer>, public Producer<MeatConsumer> { using Producer<AppleConsumer>::SetConsumer; using Producer<MeatConsumer >::SetConsumer; };
2,713,289
2,713,327
How to execute Javascript function in C++
Please tell me, how to include a javascript header file or javascript function in C++ code. The C++ code is written in Linux(UBUNTU)? Although i need to perform the above action only, but let me tell u my purpose of doing it, as i am intending to implement CTI (Computer Telephony Integration) operation. (Help will be appreciated) Thanks a lot in advance
Calling Scripting functions from C++ http://clipp.sourceforge.net/Tutorial/back_calling.html JavaScript Calls from C++ - CodeGuru http://www.codeguru.com/cpp/i-n/ieprogram/article.php/c4399/JavaScript-Calls-from-C.htm JavaScript call from C++ - CodeProject http://www.codeproject.com/KB/COM/jscalls.aspx calling javascript from c++ code - JavaScript / Ajax / DHTML answers http://bytes.com/topic/javascript/answers/759793-calling-javascript-c-code Try All of above this.
2,713,314
2,713,501
Expose C++ object to Javascript in Qt
Is there any way I can expose a C++ object/function to JavaScript running inside the QtWebKit browser in Qt? It's possible to expose ActionScript objects to JS code running inside the WebKit browser in Adobe AIR - I'm looking for similar functionality in Qt.
Yes. Take a look at this. It should be a good start.
2,713,496
2,713,518
Parsing HTML to find specific links (Without Keywords)
I posted about this sort of earlier, but I am not sure how to post back to my original question as I can only comment or answer my own question. Anyways, I need to get 4 links from a website, the latest stable build links for windows and linux, and the latest development build links for windows and linux (4 links total) within my C++ application. I can download the page (http://www.sourcemod.net/snapshots.php) with LibCURL which is already implemented in the project, but after that I am not sure. I was looking at parsers, but I can't think of how I am going to discern link from link. Obviously using a parser I could get the first link from each table, but this does not seem efficient and would only provide me with the links to windows builds. It looks like the links I need will be in the fourth in both tables, but I am just very familiar with a good way to go about this, so any help would be appreciated.
Maybe you'll find the location of the actual downloads, http://www.sourcemod.net/smdrop/, easier to parse.
2,713,509
2,713,524
Auto pointer for unsigned char array?
I'd need a class like std::auto_ptr for an array of unsigned char*, allocated with new[]. But auto_ptr only calls delete and not delete[], so i can't use it. I also need to have a function which creates and returns the array. I came out with my own implementation within a class ArrayDeleter, which i use like in this example: #include <Utils/ArrayDeleter.hxx> typedef Utils::ArrayDeleter<unsigned char> Bytes; void f() { // Create array with new unsigned char* xBytes = new unsigned char[10]; // pass array to constructor of ArrayDeleter and // wrap it into auto_ptr return std::auto_ptr<Bytes>(new Bytes(xBytes)); } ... // usage of return value { auto_ptr<Bytes> xBytes(f()); }// unsigned char* is destroyed with delete[] in destructor of ArrayDeleter Is there a more elegant way to solve this? (Even using another "popular" library)
Boost has a variety of auto-pointers, including ones for arrays. Have you considered if std::vector is sufficient? Vectors are guaranteed to be contiguous in memory, and if you know the size and allocate memory ahead of time via reserve() or resize(), the location in memory will not change.
2,713,687
2,714,156
Speed of QHash lookups using QStrings as keys
I need to draw a dynamic overlay on a QImage. The component parts of the overlay are defined in XML and parsed out to a QHash<QString, QPicture> where the QString is the name (such as "crosshairs") and the QPicture is the resolution independent drawing. I then draw components of the overlay as they are needed at a position determined during runtime. Example: I have 10 pictures in my QHash composing every possible element in a HUD. During a particular frame of video I need to draw 6 of them at different positions on the image. During the next frame something has changed and now I only need to draw 4 of them but 2 of those positions have changed. Now to my question: If I am trying to do this quickly, should I redefine my QHash as QHash<int, QPicture> and enumerate the keys to counteract the overhead caused by string comparisons; or are the comparisons not going to make a very big impact on performance? I can easily make the conversion to integer keys as the XML parser and overlay composer are completely separate classes; but I would like to use a consistent data structure across the application. Should I overcome my desire for consistency and re-usability in order to increase performance? Will it even matter very much if I do?
Gareth has the right answer of course. I'd like to extend it a tiny bit. Go for consistency and reusability first. Try not introduce huge performance bottlenecks too; it's hard to strike the balance Set realistic performance criteria. I'm guessing you are making something game-like, a reasonable criteria would be "sustaining 25 fps on my dev machine" Is your application meeting the criteria? Yes? Enough optimizations, go to 5. Profile your application, optimize the parts that take the most time. Go back to 3. Profit! Back to your concrete question, if the number of elements in your hash table is less than or about a hundred, the key type probably won't matter at all.
2,713,698
2,713,746
NCurses-Like System for Windows
Are there any C++ libraries similar to Ncurses, but for Windows? It seems there are no ports of Ncurses and I need a really good display system like it. Any suggestions? Cross-platform is a plus.
There is very similar library PDCurses. It uses the same calls as ncurses, but works on Win32. The only thing you'd need to port a program would be to recompile. http://pdcurses.sourceforge.net/
2,713,931
2,772,002
Low Throughput on Windows Named Pipe Over WAN
I'm having problems with low performance using a Windows named pipe. The throughput drops off rapidly as the network latency increases. There is a roughly linear relationship between messages sent per second and round trip time. It seems that the client must ack each message before the server will send the next one. This leads to very poor performance, I can only send 5 (~100 byte) messages per second over a link with an RTT of 200 ms. The pipe is asynchronous, using multiple overlapped write operations (and multiple overlapped reads at the client end), but this is not improving throughput. Is it possible to send messages in parallel over a named pipe? The pipe is created using PIPE_TYPE_MESSAGE, would PIPE_READMODE_BYTE work better? Is there any other way I can improve performance? This is a deployed solution, so I can't simply replace the pipe with a socket connection (I've read that Windows named pipe aren't recommended for use over a WAN, and I'm wondering if this is why). I'd be grateful for any help with this matter.
I've implemented a work around, introducing a small (~1ms) fixed delay to buffer up as much data as possible before writing to the pipe. Over a network link with a RTT of 200ms, I can send ten times as much data in about a third of the time. I send a message down the pipe when it first connects, so the client can determine the comms mode supported by the server and send data accordingly.
2,714,129
2,714,146
How to know if an enumerator has reached the end of the collection in C#?
I am porting a library from C++ to C#. The old library uses vectors from C++ and in the C# I am using generic Dictionaries because they're actually a good data structure for what I'm doing (each element has an ID, then I just use using TypeDictionary = Dictionary<String, Type>;). Now, in the C# code I use a loop like this one TypeDictionary.Enumerator tdEnum = MyTypeDictionary.GetEnumerator(); while( tdEnum.MoveNext() ) { Type element = typeElement.Current.Value; // More code here } to iterate through the elements of the collection. The problem is that in particular cases I need to check if a certain enumerator has reached the end of the collection, in C++ I would have done a check like this: if ( tdEnum == MyTypeDictionary.end() ) // More code here But I just don't know how to handle this situation in C#, any ideas? Thank you Tommaso
Here's a pretty simple way of accomplishing this. bool hasNext = tdEnum.MoveNext(); while (hasNext) { int i = tdEnum.Current; hasNext = tdEnum.MoveNext(); } I found an online tutorial that also may help you understand how this works. http://www.c-sharpcorner.com/UploadFile/prasadh/Enumerators11132005232321PM/Enumerators.aspx
2,714,144
2,714,212
Does the usage of interfaces slow down programs?
Possible Duplicate: What is the performance cost of having a virtual method in a C++ class? Is it true that interfaces slow down programs? I have heard that this is the case because during running time each during each usage of an object implementing this interface the decision has to be made which class implementing the interface this object belongs to. I am especially interested in an answer for C++, but also in general. And if this is true, some numbers would be helpful, too. Thank you very much!
Although Billy points out that this is a lot like the other post on SO, I think it's not exactly the same... mainly because of the way this question is worded. Because Olga talks about a "decision", I almost thought that she was getting mixed up between using interfaces vs. using a derived class, and determining if the pointer to the object is of a particular class via dynamic_cast. If you are talking about using dynamic_cast, then from what I understand (and this is not based on concrete performance numbers), you will get a pretty significant performance hit. If you are talking about using interfaces, well, then I feel that the minor hit in doing a vtable lookup and extra call(s) is far outweighed by a better software design.
2,714,154
2,714,183
How to get decimal value of a unicode character in c++
For one of my opensource projects, i need to compute the decimal equivalent of a given unicode character. For example if tamil character L'அ' is given, the output should be 2949 . I am using c++ in Qt environment. I googled and could not find a solution for this. Please help if you know a solution for this.
Use the unicode() method of the QChar object (which you can get e.g. with the at method of a QString, if a QString is what you have to start with).
2,714,285
2,714,315
how to place struct in union
I have an union X. It's size is 64bits. How can I write (if possible) its declaration if I want to access those 64 bits as: 1. 4 int16_t: p,q,r,s; 2. Array of 4 int16_t: a[4] 3. 2 int32_t: n, m; 4. Array of 2 int32_t: b[2] 5. 1 int64_t z;
something like union thingie_type { struct { int16_t p,q,r,s; }; int16_t a[4]; struct { int32_t n,m; }; int32_t b[2]; int64_t z; };
2,714,355
2,714,407
Guidelines for writing flexible software?
I've been developing an interpreter in C++ for my (esoteric, if you want) programming language some time now. One of the main things that I have noticed: I start with a flexible concept, and the further I code (Tokenizer->Parser->Interpreter) the less flexible the whole system gets. For example: I didn't implement an include function at first, yet the interpreter was already up and running - I had extreme difficulties implementing it and it was just like "patching something out" later on. My system had lost flexibility very quickly. How can I learn to keep relatively small C++ projects as flexible and extensible as possible during development?
Define the structure of the project before you start coding. Outline your main objectives and think about how can you achieve that. Code the headers. Look if it's possible to implement every feature using this set of interfaces If no -> go back to (2) If yes -> code .cpp files Enjoy. Of course, this doesn't apply to really large projects. But if your design is modular, there shouldn't be any problems to divide the project into separate parts.
2,714,362
2,714,394
C++: how to declare template array as function parameter
Very similar to this post How can I declare template array as a parameter in templated function? Something like this code: template <unsigned i> void my_func (char (&a)[i]); //yes, I do need that reference
Just declare an extra template parameter, which contains the type in question. template <typename T, unsigned i> void my_func (T (&a)[i]);
2,714,424
2,714,477
Figuring out what makes a C++ class abstract in VS2008
I'm using VS2008 to build a plain old C++ program (not C++/CLI). I have an abstract base class and a non-abstract derived class, and building this: Base* obj; obj = new Derived(); fails with the error "'Derived': cannot instantiate abstract class". (It may be worth noting, however, that if I hover over Base with the cursor, VS will pop up a tooltip saying "class Base abstract", but hovering over Derived will only say "class Derived" (no "abstract")). The definitions of these classes are fairly large and I'd like to avoid manually checking if each method has been overridden. Can VS do this for me somehow? Any general tips on pinpointing the exact parts of the class' definition that make it abstract?
The compiler should tell you in the error message. The following: struct base { virtual void foo(void) = 0; virtual void bar(void) = 0; }; struct derived : base { virtual void foo(void){} }; int main(void) { derived d; } Produces: error C2259: 'derived' : cannot instantiate abstract class due to following members: 'void base::bar(void)' : is abstract see declaration of 'base::bar' It also does the same with dynamic allocation.
2,714,426
2,714,561
How to load/save C++ class instance (using STL containers) to disk
I have a C++ class representing a hierarchically organised data tree which is very large (~Gb, basically as large as I can get away with in memory). It uses an STL list to store information at each node plus iterators to other nodes. Each node has only one parent, but 0-10 children. Abstracted, it looks something like: struct node { public: node_list_iterator parent; // iterator to a single parent node double node_data_array[X]; map<int,node_list_iterator> children; // iterators to child nodes }; class strategy { private: list<node> tree; // hierarchically linked list of nodes struct some_other_data; public: void build(); // build the tree void save(); // save the tree from disk void load(); // load the tree from disk void use(); // use the tree }; I would like to implement the load() and save() to disk, and it should be fairly fast, however the obvious problems are: I don't know the size in advance; The data contains iterators, which are volatile; My ignorance of C++ is prodigious. Could anyone suggest a pure C++ solution please?
It seems like you could save the data in the following syntax: File = Meta-data Node Node = Node-data ChildCount NodeList NodeList = sequence (int, Node) That is to say, when serialized the root node contains all nodes, either directly (children) or indirectly (other descendants). Writing the format is fairly straightforward: just have a recursive write function starting at the root node. Reading isn't that much harder. std::list<node> iterators are stable. Once you've inserted the root node, its iterator will not change, not even when inserting its children. Hence, when you're reading each node you can already set the parent iterator. This of course leaves you with the child iterators, but those are trivial: each node is a child of its parents. So, after you've read all nodes you'll fix up the child iterators. Start with the second node, the first child (The first node one was the root) and iterate to the last child. Then, for each child C, get its parent and the child to its parent's collection. Now, this means that you have to set the int child IDs aside while reading, but you can do that in a simple std::vector parallel to the std::list<node>. Once you've patched all child IDs in the respective parents, you can discard the vector.
2,714,671
2,714,825
number of months between two dates - using boost's date
I've used boost::gregorian::date a bit now. I can see that there are the related months & years & weeks duration types. I can see how to use known durations to advance a given date. Qu: But how can I get the difference between two dates in months (or years or weeks) ? I was hoping to find a function like: template<typename DURATION> DURATION date_diff<DURATION>(const date& d1,const date& d2); There would need to be some handling of rounding too. This function would return the number of (say) whole months between d1 and d2.
Do you mean difference between dates (09/12 - 08/05 = 01/07 = 19months) or difference in time ((date2_seconds - date1_seconds) / seconds_per_month)? For the first case it's possible to use accessors greg_year date::year() const; greg_month date::month() const; Then difference between dates in months: int months = (data2.year() - date1.year())*12 + date2.month() - date1.month() For the second case you there is operator date_duration date::operator-(date) const; And date_duration has following useful member: long date_duration::days() const; So you can do like this: //date date1, date2 int months = (date2-date1).days()/30;
2,714,749
2,715,041
does passing __m128i objects by reference to inline function cause these objects to be moved to stack?
I'm writing transpose function for 8x16bit vectors with SSE2 intrinsics. Since there are 8 arguments for that function (a matrix of 8x8x16bit size), I can't do anything but pass them by reference. Will that be optimized by the compiler (I mean, will these __m128i objects be passed in registers instead of stack)? Code snippet: inline void transpose (__m128i &a0, __m128i &a1, __m128i &a2, __m128i &a3, __m128i &a4, __m128i &a5, __m128i &a6, __m128i &a7) { .... }
Chances are that they will not be pushed to the stack. If the function is inline the compiler will actually push the operations (code) from the called function into the callee function instead of passing the data from the caller to the callee. Now, inline is a hint, so the compiler can decide not to actually inline the call and then you would have to follow Zan's advice and actually check what the compiled code looks like.
2,714,784
2,714,823
Start and run a class member function in background, in QT/C++
Once a minute I want to run a task, not blocking other GUI functions. I heared somthing about QConcurent::run ... Or should I use signals and slots?
Use QConcurrent it sounds like what you need. And you can use QFutureWatcher to get signals when it's done (which uses signals and slots)
2,715,045
2,715,640
C++ class is not being included properly
I have a problem which is either something I have completely failed to understand, or very strange. It's probably the first one, but I have spent the whole afternoon googling with no success, so here goes... I have a class called Schedule, which has as a member a vector of Room. However, when I compile using cmake, or even by hand, I get the following: In file included from schedule.cpp:1: schedule.h:13: error: ‘Room’ was not declared in this scope schedule.h:13: error: template argument 1 is invalid schedule.h:13: error: template argument 2 is invalid schedule.cpp: In constructor ‘Schedule::Schedule(int, int, int)’: schedule.cpp:12: error: ‘Room’ was not declared in this scope schedule.cpp:12: error: expected ‘;’ before ‘r’ schedule.cpp:13: error: request for member ‘push_back’ in ‘((Schedule*)this)->Schedule::_sched’, which is of non-class type ‘int’ schedule.cpp:13: error: ‘r’ was not declared in this scope Here are the relevant bits of code: #include <vector> #include "room.h" class Schedule { private: std::vector<Room> _sched; //line 13 int _ndays; int _nrooms; int _ntslots; public: Schedule(); ~Schedule(); Schedule(int nrooms, int ndays, int ntslots); }; Schedule::Schedule(int nrooms, int ndays, int ntslots):_ndays(ndays), _nrooms(nrooms),_ntslots(ntslots) { for (int i=0; i<nrooms;i++) { Room r(ndays,ntslots); _sched.push_back(r); } } In theory, g++ should compile a class before the one that includes it. There are no circular dependencies here, it's all straightforward stuff. I am completely stumped on this one, which is what leads me to believe that I must be missing something. :-D Edit: The contents of room.h from the comments below: #include <vector> #include "day.h" class Room { private: std::vector<Day> _days; public: Room(); Room(int ndays, int length); ~Room(); };
It may not matter, I but I see no include guards in your headers. Shouldn't matter, but just to cover any angle...
2,715,063
2,715,117
Problem with reading file line-by-line
I'm trying to complete an exercise to write a program that takes the following command line arguments: an input file, an output file, and an unspecified number of words. The program is to read the contents of the input file line by line, find for each word given which lines contain the word, and print the lines with their line number to the output file. Here's my code: #include <iostream> #include <fstream> #include <string> #include <sstream> using namespace std; int main(int argc, char* argv[]) { if (argc < 4) { cerr << "Error #1: not enough arguments provided\n"; return 1; } ifstream in(argv[1]); if (!in.is_open()) { cerr << "Error #2: input file could not be opened\n"; return 2; } ofstream out(argv[2]); if (!out.is_open()) { cerr << "Error #3: output file could not be opened\n"; return 3; } ostringstream oss; for (int i = 3; i < argc; ++i) { int k = 0; string temp; oss << argv[i] << ":\n\n"; while (getline(in, temp)) { ++k; unsigned x = temp.find(argv[i]); if (x != string::npos) oss << "Line #" << k << ": " << temp << endl; } } string copy = oss.str(); out << copy; in.close(); out.close(); return 0; } If I try to run that, I get the predicted output for the first word given, but any words following it aren't found. For example, for the source code above will give the following output: in: Line #1: #include <iostream> Line #2: #include <fstream> Line #3: #include <string> Line #4: #include <sstream> Line #5: using namespace std; Line #7: int main(int argc, char* argv[]) { Line #12: ifstream in(argv[1]); Line #13: if (!in.is_open()) { Line #14: cerr << "Error #2: input file could not be opened\n"; Line #22: ostringstream oss; Line #23: string temp; Line #24: for (int i = 3; i < argc; ++i) { Line #26: int k = 0; Line #28: while (getline(in, temp)) { Line #30: unsigned x = temp.find(argv[i]); Line #31: if (x != string::npos) Line #32: oss << "Line #" << k << ": " << temp << endl; Line #35: string copy = oss.str(); Line #37: in.close(); out: That is, it'll find all the instances of the first word given but not any following. What am I doing wrong here? EDIT: I had been trying to figure out a way to go back to the beginning of the file, but I sorta gave up after I couldn't find a method called "rewind()" or something like that. I added in.seekg(0, ios::beg) after the while loop, and it still gives me the same wrong output. EDIT 2: Okay, I finally gave in and realized I wouldn't be able to get my original desired output without some sort of wild attempt at using vectors of pairs, so I gave in and decided to make it print in this form: found in at line #31: cerr << "Error #2: input file could not be opened\n"; found out at line #34: ofstream out(argv[2]); That is, it prints all the lines in order and heads each one with the specific word found. Here's the while-loop: ostringstream oss; string temp; while(getline(in,temp)) { static int count = 1; for (int i = 3; i < argc; ++i) { unsigned foundWord = temp.find(argv[i]); if (foundWord != string::npos) oss << "found " << argv[i] << " at line #" << count << ": " << temp << endl; } ++count; } Anyway, thanks for all the help! The exercise itself didn't say the output had to be formatted in any way, so I consider it fully completed.
You are looping through the strings you are looking for, but you have the getline() that reads the file in the loop. You really want: for each input line getline for each string we are looking for is string in line?
2,715,164
2,715,214
How can I decode the boost library naming?
I tried to find out that gd means in boost library name and I only found two other people looking for the same thing. I suppose it should be a place where this is clearly documented and I would like to find it. mt - multitheaded, get it with bjam threading=multi s - bjam runtime-link=static g - using debug versions of the standard and runtime support libraries. what bjam switch??? d - debug bjam variant=debug Update How do I control what bjam switches controls the above variants? In fact the only one that I wasn't able to identify is the g.
See Boost getting started windows section 6.3 naming and section 6.1 on Unix naming The ones that deal with -mt and d are -mt Threading tag: indicates that the library was built with multithreading support enabled. Libraries built without multithreading support can be identified by the absence of `-mt`. -d ABI tag: encodes details that affect the library's interoperability with other compiled code. For each such feature, a single letter is added to the tag as listed in this table: Key Use this library when (Boost.Build option) s linking statically to the C++ standard library and compiler runtime support libraries. (runtime-link=static) g using debug versions of the standard and runtime support libraries. (runtime-debugging=on) y using a special debug build of Python. (python-debugging=on) d building a debug version of your code. (variant=debug) p using the STLPort standard library rather than the default one supplied with your compiler. (stdlib=stlport)
2,715,198
2,715,248
C++ Pointer Objects vs. Non Pointer Objects
Possible Duplicate: Why would you ever want to allocate memory on the heap rather than the stack? Test2 *t2 = new Test2(); t2->test(); Test2 t3; t3.test(); Why would I want to create a pointer object of type Test2? Why not just do non pointer version of Test2? Why would I want to do pointer objects? Found answer here: Why would you ever want to allocate memory on the heap rather than the stack? When is it best to use a stack instead of a heap and vice versa? When to use "new" and when not to in C++? When should I use the new keyword in C++? Proper stack and heap usage in C++ Stack, Static and Heap in C++
The reasons to use dynamic storage include (but probably not limited to) Manual control of the objects lifetime - the object will live until you explicitly destroy it Creating as many objects as necessary, when the final number of objects is only known at run-time (like number of nodes in a tree or number of elements in an array). Run-time control of the object's type (like actual type of polymorphic object). When it makes no difference, it is always better to create the object using your t3 method. Don't use dynamic memory unless you have to. But sometimes you really have to (see the reasons above).
2,715,273
10,994,547
OpenAL and Vista: Device is always 'Generic Software'
I'm writing the audio part of a game, and I'm using OpenAL. I want to use some extensions, but the tests always fail: TRACE: AudioManager - Sound device: 'Generic Software' TRACE: AudioManager - Enabling OpenAL extensions... TRACE: AudioManager - Compressor support: NO TRACE: AudioManager - Reverb support: YES TRACE: AudioManager - Chorus support: NO TRACE: AudioManager - Distortion support: NO TRACE: AudioManager - Echo support: NO TRACE: AudioManager - Flanger support: NO TRACE: AudioManager - Frequency shifter support: NO TRACE: AudioManager - Vocal morpher support: NO TRACE: AudioManager - Pitch shifter support: NO TRACE: AudioManager - Ring modulator support: NO TRACE: AudioManager - AutoWAH support: NO TRACE: AudioManager - Equalizer support: NO TRACE: AudioManager - EAX Reverb support: YES This is because I only get the Generic Software driver, which only supports reverb and EAX reverb. And not just on my machine, but others as well. Here's how I detect the drivers for OpenAL to use: ALchar device[256]; ZeroMemory(device, 256); if (alcIsExtensionPresent(NULL, "ALC_ENUMERATE_ALL_EXT")) { strcpy_s(device, 256, alcGetString(NULL, ALC_ALL_DEVICES_SPECIFIER)); } else if (alcIsExtensionPresent(NULL, "ALC_ENUMERATION_EXT")) { strcpy_s(device, 256, alcGetString(NULL, ALC_DEVICE_SPECIFIER)); } TRACE_AUDIOMANAGER("Sound device: '%s'", device); g_System = alcOpenDevice(device); According to the specification, the device specifier should return two drivers: 'Generic Hardware' and 'Generic Software', separated by a NULL terminator. My sound card is an "NVIDIA High Definition Audio" device which is using the nvhda32v.sys driver (version 1.0.0.63, updated on 11-11-2009). Why doesn't OpenAL detect my hardware?
OpenAL should always return the default audio device, unless you are using a Creative audio card. The extensions are all Creative-specific. It's the same as expecting to get Intel-specific OpenGL extension on an NVIDIA videocard. For the record, here's how you set up OpenAL: // create a default device ALCdevice* device = alcOpenDevice(""); if (!device) { LOG_ERROR("Could not create OpenAL device."); return false; } // context attributes, 2 zeros to terminate ALint attribs[6] = { 0, 0 }; ALCcontext* context = alcCreateContext(device, attribs); if (!context) { LOG_ERROR("Could not create OpenAL context."); alcCloseDevice(device); return false; } if (!alcMakeContextCurrent(context)) { LOG_ERROR("Could not enable OpenAL context."); alcDestroyContext(context); alcCloseDevice(device); return false; } LOG_INFO("[OpenAL] Version: %s", alGetString(AL_VERSION)); LOG_INFO("[OpenAL] Vendor: %s", alGetString(AL_VENDOR)); LOG_INFO("[OpenAL] Renderer: %s", alGetString(AL_RENDERER));
2,715,340
2,715,404
Automatically converting an A* into a B*
Suppose I'm given a class A. I would like to wrap pointers to it into a small class B, some kind of smart pointer, with the constraint that a B* is automatically converted to an A* so that I don't need to rewrite the code that already uses A*. I would therefore want to modify B so that the following compiles... struct A { void foo() {} }; template <class K> struct B { B(K* k) : _k(k) {} //operator K*() {return _k;} //K* operator->() {return _k;} private: K* _k; }; void doSomething(A*) {} void test() { A a; A* pointer_to_a (&a); B<A> b (pointer_to_a); //b->foo(); // I don't need those two... //doSomething(b); B<A>* pointer_to_b (&b); // Following represents existing code I don't want to change... pointer_to_b->foo(); // 'foo' : is not a member of 'B<K>' doSomething(pointer_to_b); // 'doSomething' : cannot convert parameter 1 from 'B<K> *' to 'A *' } Note that B inheriting from A is not an option (instances of A are created in factories out of my control)... Is it possible? Thanks.
The type of pointer_to_b is pointer to B, which is a type you cannot modify; it's implemented by the compiler. You can do (*pointer_to_b)->foo(), which will do the right thing (assuming you have the overridden operator->()). However, that won't let the other code do the right thing, if you pass pointer_to_be into it. Also let me add that you can override operator& on B to return an A*, which might solve your problem, depending on the specific use cases.
2,715,386
2,715,411
C++ runtime, display exception message
I am using gcc on linux to compile C++ code. There are some exceptions which should not be handled and should close program. However, I would like to be able to display exception string: For example: throw std::runtime_error(" message"); does not display message, only type of error. I would like to display messages as well. Is there way to do it? it is a library, I really do not want to put catch statements and let library user decide. However, right now library user is fortran, which does not allow to handle exceptions. in principle, I can put handlers in wrapper code, but rather not to if there is a way around
Standard exceptions have a virtual what() method that gives you the message associated with the exception: int main() { try { // your stuff } catch( const std::exception & ex ) { cerr << ex.what() << endl; } }
2,715,563
2,715,584
how to apply shader to specific object
I have several objects on my scene. I want to apply my shader to one of them only. Environment: OpenGL 2.0, C++, GLUT, GLEW.
The shader program is only in effect for as long as it is installed. Only the draw calls you make while the program is installed will use the shader. You must install your shader, draw your object, and then uninstall the shader. Edit: By "install" the shader I mean use glUseProgram with your shader's handle. By "uninstall" I mean either installing another shader or calling glUseProgram with an argument of 0. See glUseProgram. My "install/uninstall" terminology comes from there.
2,715,884
2,716,247
How to get a debug flow of execution in C++
I work on a global trading system which supports many users. Each user can book,amend,edit,delete trades. The system is regulated by a central deal capture service. The deal capture service informs all the user of any updates that occur. The problem comes when we have crashes, as the production environment is impossible to re-create on a test system, I have to rely on crash dumps and log files. However this doesn't tell me what the user has been doing. I'd like a system that would (at the time of crashing) dump out a history of what the user has been doing. Anything that I add has to go into the live environment so it can't impact performance too much. Ideas wise I was thinking of a MACRO at the top of each function which acted like a stack trace (only I could supply additional user information, like trade id's, user dialog choices, etc ..) The system would record stack traces (on a per thread basis) and keep a history in a cyclic buffer (varying in size, depending on how much history you wanted to capture). Then on crash, I could dump this history stack. I'd really like to hear if anyone has a better solution, or if anyone knows of an existing framework? Thanks Rich
Your solution sounds pretty reasonable, though perhaps rather than relying on viewing your audit trail in the debugger you can trigger it being printed with atexit() handlers. Something as simple as a stack of strings that have __FILE__,__LINE__,pthread_self() in them migth be good enough You could possibly use some existing undo framework, as its similar to an audit trail, but it's going to be more heavyweight than you want. It will likely be based on the command pattern and expect you to implement execute() methods, though I suppose you could just leave them blank.
2,715,931
2,715,993
Composite pattern in C++
I have to work with an application in C++ similar to a phone book: the class Agenda with an STL list of Contacts.Regarding the contacts hierarchy,there is a base-class named Contact(an abstract one),and the derived classes Friend and Acquaintance(the types of contact). These classes have,for instance, a virtual method called getName,which returns the name of the contact. Now I must implement the Composite pattern by adding another type of contact,Company(being derived from Contact),which also contains a collection of Contacts(an STL list as well),that can be either of the "leaf" type(Friends or Acquaintances),or they can be Companies as well. Therefore,Company is the Compound type. The question is: how and where can I implement an STL find_if to search the contact with a given name(via getName function or suggest me smth else) both among the "leaf"-type Contact and inside the Company collection? In other words,how do I traverse the tree in order to find possible matches there too,using an uniform function definition? I hope I was pretty clear...
Well, one way to do it: virtual contact* contact::findContact(std::string name) { if(m_name == name) {return this;} return NULL; } Then: contact * Company::findContact(std::string name) { if(!contact::findContact(name) ) { //For each contact in the contact list, findContact(name) //If we find something, return that. //Otherwise return null. } return this; } What you're doing is asking each node to find the one you're looking for, without caring what type of node (leaf or otherwise) it is. Each node then checks itself, and, for those with child nodes, their children.
2,716,018
2,717,017
How to synchronize access to many objects
I have a thread pool with some threads (e.g. as many as number of cores) that work on many objects, say thousands of objects. Normally I would give each object a mutex to protect access to its internals, lock it when I'm doing work, then release it. When two threads would try to access the same object, one of the threads has to wait. Now I want to save some resources and be scalable, as there may be thousands of objects, and still only a hand full of threads. I'm thinking about a class design where the thread has some sort of mutex or lock object, and assigns the lock to the object when the object should be accessed. This would save resources, as I only have as much lock objects as I have threads. Now comes the programming part, where I want to transfer this design into code, but don't know quite where to start. I'm programming in C++ and want to use Boost classes where possible, but self written classes that handle these special requirements are ok. How would I implement this? My first idea was to have a boost::mutex object per thread, and each object has a boost::shared_ptr that initially is unset (or NULL). Now when I want to access the object, I lock it by creating a scoped_lock object and assign it to the shared_ptr. When the shared_ptr is already set, I wait on the present lock. This idea sounds like a heap full of race conditions, so I sort of abandoned it. Is there another way to accomplish this design? A completely different way? Edit: The above description is a bit abstract, so let me add a specific example. Imagine a virtual world with many objects (think > 100.000). Users moving in the world could move through the world and modify objects (e.g. shoot arrows at monsters). When only using one thread, I'm good with a work queue where modifications to objects are queued. I want a more scalable design, though. If 128 core processors are available, I want to use all 128, so use that number of threads, each with work queues. One solution would be to use spatial separation, e.g. use a lock for an area. This could reduce number of locks used, but I'm more interested if there's a design which saves as much locks as possible.
You could use a mutex pool instead of allocating one mutex per resource or one mutex per thread. As mutexes are requested, first check the object in question. If it already has a mutex tagged to it, block on that mutex. If not, assign a mutex to that object and signal it, taking the mutex out of the pool. Once the mutex is unsignaled, clear the slot and return the mutex to the pool.
2,716,028
2,716,124
Add 2 chars without using strncpy?
How would I manually concatenate two char arrays without using the strncpy function? Can I just say char1 + char2? Or would I have to write a for loop to get individual elements and add them like this: addchar[0] = char1[0]; addchar[1] = char1[1]; etc etc addchar[n] = char2[0]; addchar[n+1] = char2[1]; etc etc To clarify, if char1 = "happy" char2 = "birthday" I want addchar to = happybirthday
If you consider two trivial loops to be "manual", then yes, without using the standard library this is the only way. char *append(const char *a, const char *b) { int i = 0; size_t na = strlen(a); size_t nb = strlen(b); char *r = (char*)calloc(na + nb + 1, 1); for (i = 0; i < na; i++) { r[i] = a[i]; } for (i = 0; i < nb; i++) { r[na + i] = b[i]; } return r; } Remember to call free.
2,716,041
2,716,104
What would the destructor for this class look like?
class Equipment { std::vector<Armor*> vEquip; Weapon* mainWeapon; int totalDefense; int totalAttack; public: unsigned int GetWeight(); int * GetDefense(); bool EquipArmor(Armor* armor); bool UnequipArmor(Armor* armor); bool EquipWeapon(Weapon* wep); bool UnequipWeapon(Weapon* wep); Equipment(); virtual ~Equipment(); }; It seems like there should be no destructor. The vector of pointers will take care of itself when it goes out of scope, and the actual objects the pointers point to don't need to be deleted as there will be other references to it. All of the objects in this refer to the main Container: class Container { int weightLimit; unsigned int currWeight; std::vector<Item*> vItems; public: bool AddItem(Item* item); bool RemoveItem(Item* item); Container(); Container(int weightLim); Container(int weightLim, std::vector<Item*> items); ~Container(); }; Now here I can see it being necessary to delete all objects in the container, because this is where all the objects are assigned via AddItem(new Item("Blah")) (Armor and Weapon inherit from Item)
Non-pointer types will take care of themselves. So, ints, floats, objects, etc. will take care of themselves, and you don't have to worry about deleting them. Any pointers that are managed by the class need to be deleted by that class' destructor. So, if the memory pointed to by the pointer was allocated in the class or if it was given to that class with the idea that that class would manage it, then the destructor needs to delete the pointer. If the pointer is to memory that another class is managing, then you obviously don't want your destructor to delete it. That's the job of the class that is in charge of the memory pointed to by that pointer. Standard containers do not manage the pointers that they hold if they hold pointers. So, if you have a container of pointers, whichever class is supposed to manage them needs to delete them. Odds are that that's the class that holds the container, but that depends on what your code is doing. So, typically, for a class that has a container of pointers, you'll need something like this in the destructor: for(containerType<T*>::iterator iter = container.begin(), end = container.end(); iter != end; ++iter) { delete *iter; } Every pointer that has memory allocated to it has to have something (generally a class, but sometimes the function that it's allocated in) who effectively owns that memory and makes sure that it is freed. When talking about classes, that's usually the same class that the memory is allocated in, but of course, it's quite possible for one class or function to allocate the memory and then effectively pass on the ownership of that memory to another class or function. Regardless, whoever "owns" the memory needs to deal with cleaning it up. That's what your destructor needs to worry about: cleaning up any resources that that class owns.
2,716,079
2,716,140
C++ beginner question regarding chars
I'm just messing around with some C++ at the moment trying to make a simple tic-tac-toe game and I'm running into a bit of a problem. This is my code: #include <iostream> using namespace std; class Square { public: char getState() const; void setState(char); Square(); ~Square(); private: char * pState; }; class Board { public: Board(); ~Board(); void printBoard() const; Square getSquare(short x, short y) const; private: Square board[3][3]; }; int main() { Board board; board.getSquare(1,2).setState('1'); board.printBoard(); return 0; } Square::Square() { pState = new char; *pState = ' '; } Square::~Square() { delete pState; } char Square::getState() const { return *pState; } void Square::setState(char set) { *pState = set; } Board::~Board() { } Board::Board() { } void Board::printBoard() const { for (int x = 0; x < 3; x++) { cout << "|"; for (int y = 0; y < 3; y++) { cout << board[x][y].getState(); } cout << "|" << endl; } } Square Board::getSquare(short x, short y) const { return board[x][y]; } Forgive me if there are blatantly obvious problems with it or it's stupidly written, this is my first program in C++ :p However, the problem is that when I try and set the square 1,2 to the char '1', it doesn't print out as a 1, it prints out as some strange character I didn't recognise. Can anyone tell me why? :) Thanks in advance.
You don't need to use new for creating instances of variables. Try changing your state variable to char instead of char * (pointer to char). In general, the char * type is used to indicate a collection (array) of characters terminated by a nul character. Also, set is a data type in the std namespace. Just change the name to something else, such as new_value. The getState() method is returning a copy of the state, not a reference to the state. This where Java and C++ differ. Try returning a State&, which is C++ jargon for a reference to a State instance. Your program is a bit overkill for a Tic-Tac-Toe game; the ancient ones used arrays of char instead of this new fashioned stuff called OO.
2,716,134
2,716,141
pointers to functions
I have two basic Cpp tasks, but still I have problems with them. First is to write functions mul1,div1,sub1,sum1, taking ints as arguments and returning ints. Then I need to create pointers ptrFun1 and ptrFun2 to functions mul1 and sum1, and print results of using them. Problem starts with defining those pointers. I thought I was doing it right, but devcpp gives me errors in compilation. #include <iostream> using namespace std; int mul1(int a,int b) { return a * b; } int div1(int a,int b) { return a / b; } int sum1(int a,int b) { return a + b; } int sub1(int a,int b) { return a - b; } int main() { int a=1; int b=5; cout << mul1(a,b) << endl; cout << div1(a,b) << endl; cout << sum1(a,b) << endl; cout << sub1(a,b) << endl; int *funPtr1(int, int); int *funPtr2(int, int); funPtr1 = sum1; funPtr2 = mul1; cout << funPtr1(a,b) << endl; cout << funPtr2(a,b) << endl; system("PAUSE"); return 0; } 38 assignment of function `int* funPtr1(int, int)' 38 cannot convert `int ()(int, int)' to `int*()(int, int)' in assignment Task 2 is to create array of pointers to those functions named tabFunPtr. How to do that ?
Instead of int *funPtr1(int, int) you need int (*funPtr1)(int, int) to declare a function pointer. Otherwise you are just declaring a function which returns a pointer to an int. For an array of function pointers it's probably clearest to make a typedef for the function pointer type and then declare the array using that typedef. E.g. funPtr_type array_of_fn_ptrs[];
2,716,190
2,716,513
How do I use a shared library (in this case JsonCpp) in my C++ program on Linux?
I'm a new-ish C++ programmer, and I'm doing my first program on my own using C++. I decided I would like to use JSON to store some of the data I'm going to be using, and I've found a library to handle JSON, JsonCpp. I've installed the library using my Linux system's package manager, and in my C++ code, I've used in my source code file #include <json> and compiled it using g++ and it's -ljson and -L/usr/lib options (libjson.so is located in /usr/lib). However, the first usage of Json::Value, an object provided by the library, gives a compilation error of "Json has not declared". I'm sure my mistake is something simple, so could someone explain what I'm doing wrong? None of the books I had mention how to use shared libraries, so I've had to google to find this much. EDIT: g++ with the -E option gives this error: json: no such file or directory.
I checked the file list of JsonCPP: include/json/autolink.h [code] include/json/config.h [code] include/json/features.h [code] include/json/forwards.h [code] include/json/json.h [code] include/json/reader.h [code] include/json/value.h [code] include/json/writer.h [code] Try #include <json/json.h> if the headers are installed in /usr/include. If they're installed somewhere else, mention this path with -I g++ -I/my/lib/include -L/my/lib/lib -lmylib mysource.cpp
2,716,293
2,716,432
Trying to 'Make' CUDA SDK, ld cannot find library, ldconfig says it can
I know there are many other questions similar to this one, but none of the solutions posited there are working for me Basically, making the SDK sample files, i get /usr/bin/ld: cannot find -lcuda which would be an easy enough 'find the library and throw it to ldconfig', except ldconfig already says it has it... $ sudo ldconfig -v | grep cuda /usr/local/cuda/lib64: libcudartemu.so.3 -> libcudartemu.so.3.0.14 libcudart.so.3 -> libcudart.so.3.0.14 /usr/local/cuda/lib: libcudartemu.so.3 -> libcudartemu.so.3.0.14 libcudart.so.3 -> libcudart.so.3.0.14 libcuda.so.1 -> libcuda.so.195.36.15 libcuda.so.1 -> libcuda.so.195.36.15 libicudata.so.42 -> libicudata.so.42.1 And I checked, there is a symlink libcuda.so -> libcuda.so.1 but I'm still confused as to why libcuda.so -> ... doesnt show up I must be missing something really obvious. Any ideas?
ldconfig deals only with runtime libraries, whereas ld deals with build-time libraries. Depending on how you installed the CUDA libraries, you may need to install an additional package for the symlink used at buildtime, or you may need to pass a -L option to gcc or ld in order to tell it where the build-time symlink is.
2,716,362
2,716,412
How to call DOS Interrupts within a C/C++ program using Inline Assembly?
I need to call some DOS interrupts (Services) from a C/C++ program, I tried the following inline asm code: (Read a character) int main() { asm( "movb $0x01, %ah;" "int $0x21" ); system("PAUSE"); } But it did not work ! I would like to know what have i done wrong here ! Also if there is another way to call dos interrupts ! Thank You !
You can only use DOS interrupts from DOS programs, so to make this work, you'd need a really ancient C++ compiler like Visual C++ 1.0 or 1.5, or Turbo C++/Borland C++ up through something like 4.5 or possibly 5.0. Then you'd have to fix your assembly code -- what you've written looks like AT&T syntax, but all the DOS compilers of which I'm aware use Intel syntax. There is one semi-exception to that: djgcc. This an ancient version of gcc that runs under a DOS extender, so it uses AT&T syntax, and still supports a set of DOS-like interrupts (though you're really using the DOS extender, not DOS per se). Even then, the program would only run on a system that supports DOS programs (and Microsoft is quickly dropping that from windows -- e.g., it's absent in all the x64 versions of Windows). DOS has been obsolete long enough that writing new code for it doesn't make sense. If you want to read a key like that, write a Windows program, and use something like ReadConsoleInput instead. Edit: Okay, if you really want to do this, the obvious way would be to pick a DOS extender and port a current version of gcc to it. The other possibility would be to pick a compiler like OpenWatcom or Digital Mars that's still maintained and already ported to a DOS extender.
2,716,749
2,716,989
Throwing a new exception while throwing an old exception
If a destructor throws in C++ during stack unwinding caused by an exception, the program terminates. (That's why destructors should never throw in C++.) Example: struct Foo { ~Foo() { throw 2; // whoops, already throwing 1 at this point, let's terminate! } }; int main() { Foo foo; throw 1; } terminate called after throwing an instance of 'int' This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information. If a finally block is entered in Java because of an exception in the corresponding try block and that finally block throws a second exception, the first exception is silently swallowed. Example: public static void foo() throws Exception { try { throw new Exception("first"); } finally { throw new Exception("second"); } } public static void main(String[] args) { try { foo(); } catch (Exception e) { System.out.println(e.getMessage()); // prints "second" } } This question crossed my mind: Could a programming language handle multiple exceptions being thrown at the same time? Would that be useful? Have you ever missed that ability? Is there a language that already supports this? Is there any experience with such an approach? Any thoughts?
Think in terms of flow control. Exceptions are fundamentally just fancy setjmp/longjmp or setcc/callcc anyway. The exception object is used to select a particular place to jump to, like an address. The exception handler simply recurses on the current exception, longjmping until it is handled. Handling two exceptions at a time is simply a matter of bundling them together into one, such that the result produces coherent flow control. I can think of two alternatives: Combine them into an uncatchable exception. It would amount to unwinding the entire stack and ignoring all handlers. This creates the risk of an exception cascade causing totally random behavior. Somehow construct their Cartesian product. Yeah, right. The C++ methodology serves the interest of predictability well.
2,716,917
2,717,108
Adapting Map Iterators Using STL/Boost/Lambdas
Consider the following non-working code: typedef map<int, unsigned> mymap; mymap m; for( int i = 1; i < 5; ++i ) m[i] = i; // 'remove' all elements from map where .second < 3 remove_if(m.begin(), m.end(), bind2nd(less<int>(), 3)); I'm trying to remove elements from this map where .second < 3. This obviously isn't written correctly. How do I write this correctly using: Standard STL function objects & techniques using bind + less<> but without having to write a custom functor Boost.Bind C++0x Lambdas I know I'm not eraseing the elements. Don't worry about that; I'm just simplifying the problem to solve.
I'm not sure how to do this using just the STL binders but I think your main problem is that what's being passed into the functor you give to remove isn't just an int but a pair<int, unsigned>. Using boost::bind you'd do it like this: remove_if(m.begin(), m.end(), bind(&std::pair<int, unsigned>::second, _1) < 3); Using a lambda function it's something like this: remove_if(m.begin(), m.end(), [](const std::pair<int, unsigned>& p) { return p.second < 3; } ); I haven't checked that this compiles, sorry.
2,716,925
2,717,125
Remove never-run call to templated function, get allocation error on run-time
I have a piece of templated code that is never run, but is compiled. When I remove it, another part of my program breaks. First off, I'm a bit at a loss as to how to ask this question. So I'm going to try throwing lots of information at the problem. Ok, so, I went to completely redesign my test project for my experimental core library thingy. I use a lot of template shenanigans in the library. When I removed the "user" code, the tests gave me a memory allocation error. After quite a bit of experimenting, I narrowed it down to this bit of code (out of a couple hundred lines): void VOODOO(components::switchBoard &board) { board.addComponent<using_allegro::keyInputs<'w'> >(); } Fundementally, what's weirding me out is that it appears that the act of compiling this function (and the template function it then uses, and the template functions those then use...), makes this bug not appear. This code is not being run. Similar code (the same, but for different key vals) occurs elsewhere, but is within Boost TDD code. I realize I certainly haven't given enough information for you to solve it for me; I tried, but it more-or-less spirals into most of the code base. I think I'm most looking for "here's what the problem could be", "here's where to look", etc. There's something that's happening during compile because of this line, but I don't know enough about that step to begin looking. Sooo, how can a (presumably) compilied, but never actually run, bit of templated code, when removed, cause another part of code to fail? Error: Unhandled exceptionat 0x6fe731ea (msvcr90d.dll) in Switchboard.exe: 0xC0000005: Access violation reading location 0xcdcdcdc1. Callstack: operator delete(void * pUser Data) allocator< class name related to key inputs callbacks >::deallocate vector< same class >::_Insert_n(...) vector< " " >::insert(...) vector<" ">::push_back(...) It looks like maybe the vector isn't valid, because _MyFirst and similar data members are showing values of 0xcdcdcdcd in the debugger. But the vector is a member variable... Update: The vector isn't valid because it's never made. I'm getting a channel ID value stomp, which is making me treat one type of channel as another. Update: Searching through with the debugger again, it appears that my method for giving each "channel" it's own, unique ID isn't giving me a unique ID: inline static const char channel<template args>::idFunction() { return reinterpret_cast<char>(&channel<CHANNEL_IDENTIFY>::idFunction); }; Update2: These two are giving the same: slaveChannel<switchboard, ALLEGRO_BITMAP*, entityInfo<ALLEGRO_BITMAP*> slaveChannel<key<c>, char, push<char> Sooo, having another compiled channel type changing things makes sense, because it shifts around the values of the idFunctions? But why are there two idFunctions with the same value?
you seem to be returning address of the function as a character? that looks weird. char has much smaller bit count than pointer, so it's highly possible you get same values. that could reason why changing code layout fixes/breaks your program
2,716,972
2,716,999
why don't STL ifstream and ofstream classes take std::string as filenames?
This is a complaint about STL. Why do they take filename arguments as (char *) and not as std::string? This seems to make no sense. There are two other questions on this topic: How to open unicode filenames with STL Windows Codepage interactions with C++ The issue is that I have a lot of code that looks like this: std::ofstream f(fname.c_str()); WhenI would like it to look like this: std::ofstream f(fname); Additional issues that are mentioned in the above posts is the issue of UTF-16 vs. UTF-8. (UTF-16 might contain NULLs which would break the POSIX API). But that's not really an issue, because the implementation could convert UTF-16 to UTF-8 before calling open(). But seriously, this makes no sense. Are there any plans to upgrade STL?
why don’t ifstream and ofstream classes take std::string as filenames? I've seen a few sensible arguments for that (namely that this would create a dependency of the streams on strings), but frankly I believe the actual reason is that the streams are much older than the standard library and its strings. Are there any plans to upgrade STL? It's called C++11 and will be the new version of the standard. I don't know whether file streams changed. You could look at the final draft and find out for yourself. Note that STL is the name for a library of containers, algorithms, and iterators, incorporated into the standard library. Also part of the standard library are strings, streams and others. In particular, streams are not part of the STL. They are siblings.
2,717,012
2,717,104
Weird behaviour with vector::erase and std::remove_if with end range different from vector.end()
I need to remove elements from the middle of a std::vector. So I tried: struct IsEven { bool operator()(int ele) { return ele % 2 == 0; } }; int elements[] = {1, 2, 3, 4, 5, 6}; std::vector<int> ints(elements, elements+6); std::vector<int>::iterator it = std::remove_if(ints.begin() + 2, ints.begin() + 4, IsEven()); ints.erase(it, ints.end()); After this I would expect that the ints vector have: [1, 2, 3, 5, 6]. In the debugger of Visual studio 2008, after the std::remove_if line, the elements of ints are modified, I'm guessing I'm into some sort of undefined behaviour here. So, how do I remove elements from a Range of a vector?
Edit: Sorry, the original version of this was incorrect. Fixed. Here's what's going on. Your input to remove_if is: 1 2 3 4 5 6 ^ ^ begin end And the remove_if algorithm looks at all numbers between begin and end (including begin, but excluding end), and removes all elements between that match your predicate. So after remove_if runs, your vector looks like this 1 2 3 ? 5 6 ^ ^ begin new_end Where ? is a value that I don't think is deterministic, although if it's guaranteed to be anything it would be 4. And new_end, which points to the new end of the input sequence you gave it, with the matching elements now removed, is what is returned by std::remove_if. Note that std::remove_if doesn't touch anything beyond the subsequence that you gave it. This might make more sense with a more extended example. Say that this is your input: 1 2 3 4 5 6 7 8 9 10 ^ ^ begin end After std::remove_if, you get: 1 2 3 5 7 ? ? 8 9 10 ^ ^ begin new_end Think about this for a moment. What it has done is remove the 4 and the 6 from the subsequence, and then shift everything within the subsequence down to fill in the removed elements, and then moved the end iterator to the new end of the same subsequence. The goal is to satisfy the requirement that the (begin, new_end] sequence that it produces is the same as the (begin, end] subsequence that you passed in, but with certain elements removed. Anything at or beyond the end that you passed in is left untouched. What you want to get rid of, then, is everything between the end iterator that was returned, and the original end iterator that you gave it. These are the ? "garbage" values. So your erase call should actually be: ints.erase(it, ints.begin()+4); The call to erase that you have just erases everything beyond the end of the subsequence that you performed the removal on, which isn't what you want here. What makes this complicated is that the remove_if algorithm doesn't actually call erase() on the vector, or change the size of the vector at any point. It just shifts elements around and leaves some "garbage" elements after the end of the subsequence that you asked it to process. This seems silly, but the whole reason that the STL does it this way is to avoid the problem with invalidated iterators that doublep brought up (and to be able to run on things that aren't STL containers, like raw arrays).
2,717,199
2,717,413
dynamically created arrays
My task consists of two parts. First I have to create globbal char array of 100 elements, and insert some text to it using cin. Afterwards calculate amount of chars, and create dedicated array with the length of the inputted text. I was thinking about following solution : char[100]inputData; int main() { cin >> inputData >> endl; int length=0; for(int i=0; i<100; i++) { while(inputData[i] == "\0") { ++count; } } char c = new char[count]; Am I thinking good ? Second part of the task is to introduce in the first program dynamically created array of pointers to all inserted words. Adding a new word should print all the previous words and if there is no space for next words, size of the inputData array should be increased twice. And to be honest this is a bit too much for me. How I can create pointers to words specifically ? And how can I increase the size of global array without loosing its content ? With some temporary array ?
Regardless of the rest of your question, you appear to have some incorrect ideas about while loops. Let's look at this code. for(int i=0; i<100; i++) { while(inputData[i] == "\0") { ++count; } } First, "\0" is not the NUL character. It is a pointer to a string containing only the terminating NUL byte. You want '\0' instead. Assuming this change, there are still problems. Let's work through what will happen: How does a while loop work? It executes the body repeatedly, as long as the condition is true. When does a while loop finish? When the condition is finally made false by executing the body. What's the condition of your loop? inputData[i] == '\0', after correction. What's the body? ++count. Can ++count ever change the value of the condition? No, because it doesn't change i. So, if inputData[i] is not the NUL byte, the while loop never executes. But, if inputData[i] is the NUL byte, the while loop executes forever. Assuming you've read a proper string into inputData, then at some point inputData[i] will be NUL, and you'll have an infinite loop. To count the length of a standard C string, just do this count = strlen(inputData); If for some reason you really have to write a loop, then the following works: int len = 0, while (inputData[len] != '\0') { len++; } After the loop, len holds the length of the string.
2,717,318
2,718,273
How can I set the line style of a specific cell in a QTableView?
I am working with a QT GUI. I am implementing a simple hex edit control using a QTableView. My initial idea is to use a table with seventeen columns. Each row of the table will have 16 hex bytes and then an ASCII representation of that data in the seventeenth column. Ideally, I would like to edit/set the style of the seventeenth column to have no lines on the top and bottom of each cell to give the text a free flowing appearance. What is the best way to approach this using the QTableView?
I could think about a couple of ways of doing what you need; both would include drawing custom grid as it looks like there is no straight forward way of hooking into the grid painting routine of QTableView class: 1.Switch off the standard grid for your treeview grid by calling setShowGrid(false) and draw grid lines for cells which need them using item delegate. Below is an example: // custom item delegate to draw grid lines around cells class CustomDelegate : public QStyledItemDelegate { public: CustomDelegate(QTableView* tableView); protected: void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const; private: QPen _gridPen; }; CustomDelegate::CustomDelegate(QTableView* tableView) { // create grid pen int gridHint = tableView->style()->styleHint(QStyle::SH_Table_GridLineColor, new QStyleOptionViewItemV4()); QColor gridColor = static_cast<QRgb>(gridHint); _gridPen = QPen(gridColor, 0, tableView->gridStyle()); } void CustomDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { QStyledItemDelegate::paint(painter, option, index); QPen oldPen = painter->pen(); painter->setPen(_gridPen); // paint vertical lines painter->drawLine(option.rect.topRight(), option.rect.bottomRight()); // paint horizontal lines if (index.column()!=1) //<-- check if column need horizontal grid lines painter->drawLine(option.rect.bottomLeft(), option.rect.bottomRight()); painter->setPen(oldPen); } // set up for your tree view: ui->tableView->setShowGrid(false); ui->tableView->setItemDelegate(new CustomDelegate(ui->tableView)); 2.Create a QTableView descendant and override the paintEvent method. There you could either draw your own grid or let base class to draw it and then paint horizontal lines on top of the grid with using tableview's background color. hope this helps, regards
2,717,341
2,717,382
Extremely CPU Intensive Alarm Clock
EDIT: I would like to thank you all for the swift replies ^^ Sleep() works as intended and my CPU is not being viciously devoured by this program anymore! I will keep this question as is, but to let everybody know that the CPU problem has been answered expediently and professionally :D As an aside to the aside, I'll certainly make sure that micro-optimizations are kept to a minimum in the face of larger, more important problems! ================================================================================ For some reason my program, a console alarm clock I made for laughs and practice, is extremely CPU intensive. It consumes about 2mB RAM, which is already quite a bit for such a small program, but it devastates my CPU with over 50% resources at times. Most of the time my program is doing nothing except counting down the seconds, so I guess this part of my program is the one that's causing so much strain on my CPU, though I don't know why. If it is so, could you please recommend a way of making it less, or perhaps a library to use instead if the problem can't be easily solved? /* The wait function waits exactly one second before returning to the * * called function. */ void wait( const int &seconds ) { clock_t endwait; // Type needed to compare with clock() endwait = clock() + ( seconds * CLOCKS_PER_SEC ); while( clock() < endwait ) {} // Nothing need be done here. } In case anybody browses CPlusPlus.com, this is a genuine copy/paste of the clock() function they have written as an example for clock(). Much why the comment //Nothing need be done here is so lackluster. I'm not entirely sure what exactly clock() does yet. The rest of the program calls two other functions that only activate every sixty seconds, otherwise returning to the caller and counting down another second, so I don't think that's too CPU intensive- though I wouldn't know, this is my first attempt at optimizing code. The first function is a console clear using system("cls") which, I know, is really, really slow and not a good idea. I will be changing that post-haste, but, since it only activates every 60 seconds and there is a noticeable lag-spike, I know this isn't the problem most of the time. The second function re-writes the content of the screen with the updated remaining time also only every sixty seconds. I will edit in the function that calls wait, clearScreen and display if it's clear that this function is not the problem. I already tried to reference most variables so they are not copied, as well as avoid endl as I heard that it's a little slow compared to \n.
This: while( clock() < endwait ) {} Is not "doing nothing". Certainly nothing is being done inside the while loop, but the test of clock() < endwait is not free. In fact, it is being executed over and over again as fast as your system can possibly handle doing it, which is what is driving up your load (probably 50% because you have a dual core processor, and this is a single-threaded program that can only use one core). The correct way to do this is just to trash this entire wait function, and instead just use: sleep(seconds); Which will actually stop your program from executing for the specified number of seconds, and not consume any processor time while doing so. Depending on your platform, you will need to include either <unistd.h> (UNIX and Linux) or <windows.h> (Windows) to access this function.
2,717,361
2,717,429
Why isn't the copy constructor elided here?
(I'm using gcc with -O2.) This seems like a straightforward opportunity to elide the copy constructor, since there are no side-effects to accessing the value of a field in a bar's copy of a foo; but the copy constructor is called, since I get the output meep meep!. #include <iostream> struct foo { foo(): a(5) { } foo(const foo& f): a(f.a) { std::cout << "meep meep!\n"; } int a; }; struct bar { foo F() const { return f; } foo f; }; int main() { bar b; int a = b.F().a; return 0; }
It is neither of the two legal cases of copy ctor elision described in 12.8/15: Return value optimisation (where an automatic variable is returned from a function, and the copying of that automatic to the return value is elided by constructing the automatic directly in the return value) - nope. f is not an automatic variable. Temporary initializer (where a temporary is copied to an object, and instead of constructing the temporary and copying it, the temporary value is constructed directly into the destination) - nope f is not a temporary either. b.F() is a temporary, but it isn't copied anywhere, it just has a data member accessed, so by the time you get out of F() there's nothing to elide. Since neither of the legal cases of copy ctor elision apples, and the copying of f to the return value of F() affects the observable behaviour of the program, the standard forbids it to be elided. If you got replaced the printing with some non-observable activity, and examined the assembly, you might see that this copy constructor has been optimised away. But that would be under the "as-if" rule, not under the copy constructor elision rule.
2,717,513
2,717,643
C++ choose function by return type
I realize standard C++ only picks functions by argument type, not return type. I.e I can do something like: void func(int); void func(double); but not double func(); int func(); Where in the former, it's clear, in the latter, it's ambigious. Are there any extensions that lets me tell C++ to pick which function to use also by return type? Thanks!
You cannot have two functions in the same scope that have the same name and signature (ie. argument types). Yet you can create a function that will behave differently depending on what variable you assign the result to, as in: int x=f(); double x=f(); // different behaviour from above by making f() return a proxy with an overloaded cast operator. struct Proxy { operator double() const { return 1.1; } operator int() const { return 2; } }; Proxy f() { return Proxy(); } See http://ideone.com/ehUM1 Not that this particular use case (returning a different number) is useful, but there are uses for this idiom.
2,717,533
2,717,552
C++ Vector of vectors
I have a class header file called Grid.h that contains the following 2 private data object: vector<int> column; vector<vector<int>> row; And a public method whose prototype in Grid.h is such: int getElement (unsigned int& col, unsigned int& row); The definition of above mentioned function is defined as such in Grid.cpp: int getElement (unsigned int& col, unsigned int& row) { return row[row][col] ; } When I run the program, I get this error: error C2109: subscript requires array or pointer type Whats going wrong?
In the line return row[row][col]; the first row is the int&, not the vector. The variable declared in the inner scope is shadowing the variable in the outer scope, so the compiler is trying to index an int rather than a vector, which it obviously can't do. You should fix your variable names so that they don't conflict. EDIT: Also, while the error that you're getting indicates that the compiler is finding the wrong row variable, as A. Levy points out, you also have a problem with the declaration of your vector, so even if you fix the variable names, if you have indeed declared the vector as shown here, it won't compile. Nested templates need spaces between the > symbols, otherwise the compiler will read >> as a right-shift operator rather than part of a template declaration. It needs to be std::vector<std::vector<int> > row; or std::vector< std::vector<int> > row; In addition, as you're doing this in a header file, you're going to need to tack the std:: tag on the front of anything from the std namespace - such as vector. If it were in a cpp file, then you could use using namespace std; but that would be very bad to do in a header file (since it would pollute the global namespace). Without the std:: tag or the using statement, the compiler won't recognize vector.
2,717,671
2,717,762
static arrays defined with unspecified size, empty brackets?
For the C++ code fragment below: class Foo { int a[]; // no error }; int a[]; // error: storage size of 'a' isn't known void bar() { int a[]; // error: storage size of 'a' isn't known } why isn't the member variable causing an error too? and what is the meaning of this member variable? I'm using gcc version 3.4.5 (mingw-vista special) through CodeBlocks 8.02. On Visual Studio Express 2008 - Microsoft(R) C/C++ Optimizing Compiler 15.00.30729.01 for 80x86, I got the following messages: class Foo { int a[]; // warning C4200: nonstandard extension used : zero-sized array in struct/union - Cannot generate copy-ctor or copy-assignment operator when UDT contains a zero-sized array }; int a[]; void bar() { int a[]; // error C2133: 'a' : unknown size } Now, this needs some explaination too.
C99 supports something called a 'flexible' array member that is allowed to be the last member of a struct. When you dynamically allocate such a struct you can increase the amount requested from malloc() to provide for memory for the array. Some compilers add this as an extension to C90 and/or C++. So you can have code like the following: struct foo_t { int x; char buf[]; }; void use_foo(size_t bufSize) { struct foo_t* p = malloc( sizeof( struct foo_t) + bufSize); int i; for (i = 0; i < bufSize; ++i) { p->buf[i] = i; } } You can't define a struct with a flexible array member directly (as a local or a global/static variable) as the compiler won't know how much memory to allocate for it. I'm honestly not sure how you'd easily use such a thing with C++'s new operator - I think you'd have to allocate the memory for the object using malloc() and use placement new. Maybe some class/struct specific overload of operator new could be used...
2,717,700
2,717,709
Should '#include' and 'using' statements be repeated in both header and implementation files (C++)?
I'm fairly new to C++, but my understanding is that a #include statement will essentially just dump the contents of the #included file into the location of that statement. This means that if I have a number of '#include' and 'using' statements in my header file, my implementation file can just #include the header file, and the compiler won't mind if I don't repeat the other statements. What about people though? My main concern is that if I don't repeat the '#include', 'using', and also 'typedef' (now that I think of it) statements, it takes that information away from the file in which it's used, which could lead to confusion. I am just working on small projects at the moment where it won't really cause any issues, but I can imagine that in larger projects with more people working on them it could become a significant issue. An example follows: UPDATE: my function prototypes for 'Unit' have string, ostream and StringSet among their return types and parameters - I am not including anything in my header file that is used only in the implementation file. //Unit.h #include <string> #include <ostream> #include "StringSet.h" using std::string; using std::ostream; class Unit { public: //public members with string, ostream and StringSet //in their return values/parameter lists private: //private members //unrelated side-question: should private members //even be included in the header file? } ; //Unit.cpp #include "Unit.h" //The following are all redundant from a compiler perspective: #include <string> #include <ostream> #include "StringSet.h" using std::string; using std::ostream; //implementation goes here
A using-directive (using namespace std;) should not reside in a header unless it is contained within a function. It is bad practice. It is unlikely that every user of your header wants unqualified lookup for everything in a given namespace; the inclusion of unrelated headers can lead to unexpected ambiguity and compilation failures. Personally, I avoid the using-directive inside of functions for the same reasoning, but this is generally considered less harmful. A type alias (either through typedef std::string string; or using string = std::string;) should be used carefully. Type definitions have meaning, so you should never redeclare it. For example, this is an error: typedef int myint; typedef float myint; because of conflicting types. A using-declaration (using std::string; or using std::memcpy;) makes a symbol accessible for unqualified name lookup. It is extremely useful when getting for argument-dependent lookup correct, which usually doesn't matter unless you're writing a library. The advice is different depending on if you are bringing in a type or a function. Think of using-declarations with types in the same manner as a type alias: It does not make sense to have multiple definitions under the same name. With functions, all you are really doing is extending overload resolution to include a few more things (although it is usually not necessary). // Finding multiple operator<< functions makes sense using std::operator<<; using mylib::operator<<; // Finding multiple string classes does not make sense using std::string; using mylib::string; For repeating #include, you should consider if you actually need to include the file in the header in the first place. Perhaps a forward declaration fits your needs.
2,717,701
2,719,986
How can I make a proccess in an OnLButtonDown() event happen again and again untill I live the button?
What happen until now is this: Any line happens once, and if I use awhile(1) or while (nFlags == MK_LBUTTON) its working as it should but I get a crash. The other problem, or maybe the same one is the delay if I will be able to do it, maybe using while() with Timer()? I was thinking about Timer() to recall the function with delay but I can't call OnLButtonDown() because asI understand it only a message can call it with the arguments.
In OnLButtonDown() call SetTimer() to start a timer running, eg. every 100ms. Then add OnLButtonUp() and call KillTimer() to stop the timer running. Then, do your code in the OnTimer() function (add WM_TIMER to the message map) and it will run while the mouse is held down. Note if the user clicks and drags the mouse outside your window, you get OnLButtonDown() called but not OnLButtonUp() which can leave the program thinking the mouse button is stuck down. The functions to deal with this are: call SetCapture() at the same time as SetTimer() and ReleaseCapture() at the same time as KillTimer() to keep receiving mouse messages no matter where the mouse is. I'd advise looking up all the functions I've mentioned in this answer on MSDN and reading up on them for more information.
2,717,765
2,717,789
Parse <li> list with C++
I have webpage I downloaded with C++ to a string, and it is basically a massive <li> list of links. I need to find the last 2 elements of the list. Can anyone help me on how to do this?
If you are going to do it in a robust way you need an html parser. If the structure of the html is simple enough, and the runtime not an issue, something as stupid as doing string.rfind("<li>") twice might be good enough to find the positions of your elements. Then just do something even more hacky to find the end of each element like look for the next newline
2,717,854
2,717,872
How to create a dynamic array of an Abstract class?
Lets say I have an abstract class Cat that has a few concrete subclasses Wildcat, Housecat, etc. I want my array to be able to store pointers to a type of cat without knowing which kind it really is. When I try to dynamically allocate an array of Cat, it doesn't seem to be working. Cat* catArray = new Cat[200];
By creating an aray of pointers to Cat, as in Cat** catArray = new Cat*[200]; Now you can put your WildCat, HouseCat etc instances at various locations in the array for example catArray[0] = new WildCat(); catArray[1] = new HouseCat(); catArray[0]->catchMice(); catArray[1]->catchMice(); Couple of caveats, when done a) Don't forget deleting the instances allocated in catArray as in delete catArray[0] etc. b) Don't forget to delete the catArray itself using delete [] catArray; You should also consider using vector to automate b) for you
2,717,931
2,720,168
What happens in memory when a C++ class is instantiated
I'm interested in the nuts and boltw of C++ and I wondered what actually changes when an object is instantiated. I'm particularly interested if the functions are then added to memory, if they are there from runtime or if they are never stored in memory at all. If anyone could direct me to a good site on some of the core bolts of C and C++, I'd love that too. Thanks, Jo
A common case is: Memory is allocated by calling operator new. This function will most probably be already in memory, it's needed a lot. The constructor of the class is called. This code could already be in memory. If not, the call to this function page-faults. The OS notes, and loads the appropriate page from your executable into RAM. It then tells the OS to retry. ( 2A. The ctor arranges for virtual functions to be callable - often by writing a vtable pointer ) Chances are that the page with the constructor also contains the other members of your class. Those can then be called too. But if they are on another page, calling them may cause another page fault and another load. If your compiler put a vtable on a different page, the use of that vtable may also cause a page fault. The advantage of such a load-on-demand mechanism is that an OS can avoid loading the code for class CPrinter if the user never intends to print his document.
2,718,050
2,718,111
pointer reference type
I am trying to write a function that takes a pointer argument, modifies what the pointer points to, and then returns the destination of the pointer as a reference. I am getting the following error: cannot convert int*** to int* in return Code: #include <iostream> using namespace std; int* increment(int** i) { i++; return &i; } int main() { int a=24; int *p=&a; int *p2; p2=increment(&p); cout<<p2; } Thanks for helping!
If you indeed mean "return the destination of the pointer as a reference", then I think the return type you're after is int& rather than int*. This can be one of the confusing things about C++, since & and * have different meanings depending on where you use them. & is "Reference type" if you're talking about a variable definition or return type; but it means "Address of" if it's in front of a variable being used after it's defined. I could be completely mistaken, but it seems to me that you've gotten these two meanings mixed up; and since you want to return a reference, you've written "return &i", since & is used for references. However, in this case, it returns the address of i. And since i is a pointer to a pointer to an int, in this line of code: int* increment(int** i) { i++; return &i;} you are returning the address of a pointer to a pointer to an int. That is why you are getting your error message cannot convert int***' to int*. Let's walk through your code line by line. You are after a program that takes a pointer and returns a reference. So that would be: int& increment(int* i) We don't need the double pointer that you had in your code (unless you want a pointer to a pointer). Then you want it to modify what the pointer points to: (*i)++; And then return the destination of the pointer as a reference: return *i; Here, we are dereferencing i. Remember that using references lets you treat them like normal variables, and handles the pointer stuff for you. So C++ will figure out that you want it to be a reference. Then, to use your code, you can do pretty much what you had, but using less pointers: int a=24; int *p=&a; int *p2; p2 = increment(p); I haven't tested any of this, so anyone may feel free to edit my answer and fix it if I've got something wrong.
2,718,138
2,725,575
Lightweight spinlocks built from GCC atomic operations?
I'd like to minimize synchronization and write lock-free code when possible in a project of mine. When absolutely necessary I'd love to substitute light-weight spinlocks built from atomic operations for pthread and win32 mutex locks. My understanding is that these are system calls underneath and could cause a context switch (which may be unnecessary for very quick critical sections where simply spinning a few times would be preferable). The atomic operations I'm referring to are well documented here: http://gcc.gnu.org/onlinedocs/gcc-4.4.1/gcc/Atomic-Builtins.html Here is an example to illustrate what I'm talking about. Imagine a RB-tree with multiple readers and writers possible. RBTree::exists() is read-only and thread safe, RBTree::insert() would require exclusive access by a single writer (and no readers) to be safe. Some code: class IntSetTest { private: unsigned short lock; RBTree<int>* myset; public: // ... void add_number(int n) { // Aquire once locked==false (atomic) while (__sync_bool_compare_and_swap(&lock, 0, 0xffff) == false); // Perform a thread-unsafe operation on the set myset->insert(n); // Unlock (atomic) __sync_bool_compare_and_swap(&lock, 0xffff, 0); } bool check_number(int n) { // Increment once the lock is below 0xffff u16 savedlock = lock; while (savedlock == 0xffff || __sync_bool_compare_and_swap(&lock, savedlock, savedlock+1) == false) savedlock = lock; // Perform read-only operation bool exists = tree->exists(n); // Decrement savedlock = lock; while (__sync_bool_compare_and_swap(&lock, savedlock, savedlock-1) == false) savedlock = lock; return exists; } }; (lets assume it need not be exception-safe) Is this code indeed thread-safe? Are there any pros/cons to this idea? Any advice? Is the use of spinlocks like this a bad idea if the threads are not truly concurrent? Thanks in advance. ;)
You need a volatile qualifier on lock, and I would also make it a sig_atomic_t. Without the volatile qualifier, this code: u16 savedlock = lock; while (savedlock == 0xffff || __sync_bool_compare_and_swap(&lock, savedlock, savedlock+1) == false) savedlock = lock; may not re-read lock when updating savedlock in the body of the while-loop. Consider the case that lock is 0xffff. Then, savedlock will be 0xffff prior to checking the loop condition, so the while condition will short-circuit prior to calling __sync_bool_compare_and_swap. Since __sync_bool_compare_and_swap wasn't called, the compiler doesn't encounter a memory barrier, so it might reasonably assume that the value of lock hasn't changed underneath you, and avoid re-loading it in savedlock. Re: sig_atomic_t, there's a decent discussion here. The same considerations that apply to signal handlers would also apply to threads. With these changes, I'd guess that your code would be thread-safe. I would still recommend using mutexes, though, since you really don't know how long your RB-tree insert will take in the general case (per my previous comments under the question).
2,718,253
2,718,271
Only static and const variables can be assign to a class?
I am learning C++. Just curious, can only static and constant varibles be assigned a value from within the class declaration? Is this mainly why when you assign values to normal members, they have a special way doing it void myClass::Init() : member1(0), member2(1) { }
This looks like it is supposed to be a constructor; if it is, it should have no return type, and it needs to have the same name as the class, e.g., myClass::myClass() : member1(0), member2(1) { } Only a constructor can have an initializer list; you can't delegate that type of initialization to an Init function. Any nonstatic members can be initialized in the constructor initializer list. All const and reference members must be initialized in the constructor initializer list. All things being equal, you should generally prefer to initialize all members in the constructor initializer list, rather than in the body of the constructor (sometimes it isn't possible or it's clumsy to use the initializer list, in which case, you shouldn't use it, obviously).
2,718,284
2,718,294
unresolved external symbol _D3D10CreateDeviceAndSwapChain@32 referenced in function "public: bool
Having trouble creating my swap chain. I receive the following error. DX3dApp.obj : error LNK2019: unresolved external symbol _D3D10CreateDeviceAndSwapChain@32 referenced in function "public: bool __thiscall DX3dApp::InitDirect3D(void)" (?InitDirect3D@DX3dApp@@QAE_NXZ) Below is the code ive done so far. #include "DX3dApp.h" bool DX3dApp::Init(HINSTANCE hInstance, int width, int height) { mhInst = hInstance; mWidth = width; mHeight = height; if(!WindowsInit()) { return false; } if(!InitDirect3D()) { return false; } } int DX3dApp::Run() { MSG msg = {0}; while (WM_QUIT != msg.message) { while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) == TRUE) { TranslateMessage(&msg); DispatchMessage(&msg); } Render(); } return (int) msg.wParam; } bool DX3dApp::WindowsInit() { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = (WNDPROC)WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = mhInst; wcex.hIcon = 0; wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = NULL; wcex.lpszClassName = TEXT("DirectXExample"); wcex.hIconSm = 0; RegisterClassEx(&wcex); // Resize the window RECT rect = { 0, 0, mWidth, mHeight }; AdjustWindowRect(&rect, WS_OVERLAPPEDWINDOW, FALSE); // create the window from the class above mMainhWnd = CreateWindow(TEXT("DirectXExample"), TEXT("DirectXExample"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, rect.right - rect.left, rect.bottom - rect.top, NULL, NULL, mhInst, NULL); if (!mMainhWnd) { return false; } ShowWindow(mMainhWnd, SW_SHOW); UpdateWindow(mMainhWnd); return true; } bool DX3dApp::InitDirect3D() { DXGI_SWAP_CHAIN_DESC scd; ZeroMemory(&scd, sizeof(scd)); scd.BufferCount = 1; scd.BufferDesc.Width = mWidth; scd.BufferDesc.Height = mHeight; scd.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; scd.BufferDesc.RefreshRate.Numerator = 60; scd.BufferDesc.RefreshRate.Denominator = 1; scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; scd.OutputWindow = mMainhWnd; scd.SampleDesc.Count = 1; scd.SampleDesc.Quality = 0; scd.Windowed = TRUE; HRESULT hr = D3D10CreateDeviceAndSwapChain(NULL,D3D10_DRIVER_TYPE_REFERENCE, NULL, 0, D3D10_SDK_VERSION, &scd, &mpSwapChain, &mpD3DDevice); if(!hr != S_OK) { return FALSE; } ID3D10Texture2D *pBackBuffer; return TRUE; } void DX3dApp::Render() { } LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { // Allow the user to press the escape key to end the application case WM_KEYDOWN: switch(wParam) { // Check if the user hit the escape key case VK_ESCAPE: PostQuitMessage(0); break; } break; // The user hit the close button, close the application case WM_DESTROY: PostQuitMessage(0); break; } return DefWindowProc(hWnd, message, wParam, lParam); }
You are not linking against the D3D library (D3D10.lib). Add that library to your linker options (Project properties -> Linker -> Input -> Additional Dependencies). You will need to make sure the library location is in the "Additional Library Directories" path as well.
2,718,358
2,718,505
Simple question about C++ constant syntax
Here is some code copied from Thinking in C++ Vol1 Chapter 10. #include <iostream> using namespace std; int x = 100; class WithStatic { static int x; static int y; public: void print() const { cout << "WithStatic::x = " << x << endl; cout << "WithStatic::y = " << y << endl; } }; what's the meaning of const for the function print()? Thanks!
I've heard this described previously as “a method that does not logically change the object”. It means that by calling this method the caller can expect the object’s state to remain the same after the method returns. Effectively, the this pointer becomes a constant pointer to a constant instance of that class, so member variables cannot be altered. The exception to this rule is if member variables are declared with mutable. If a class has mutable member variables, these can be modified by both non-const and const methods. Also, non-const methods cannot be called from within a const method. Some people use mutable member variables to cache results of timely computations. In theory, the state of the object does not change (i.e. the only effect is that subsequent calls are quicker, but they produce the same results given the same input).
2,718,386
2,718,391
Multiple SFINAE rules
After reading the answer to this question, I learned that SFINAE can be used to choose between two functions based on whether the class has a certain member function. It's the equivalent of the following, just that each branch in the if statement is split into an overloaded function: template<typename T> void Func(T& arg) { if(HAS_MEMBER_FUNCTION_X(T)) arg.X(); else //Do something else because T doesn't have X() } becomes template<typename T> void Func(T &arg, int_to_type<true>); //T has X() template<typename T> void Func(T &arg, int_to_type<false>); //T does not have X() I was wondering if it was possible to extend SFINAE to do multiple rules. Something that would be the equivalent of this: template<typename T> void Func(T& arg) { if(HAS_MEMBER_FUNCTION_X(T)) //See if T has a member function X arg.X(); else if(POINTER_DERIVED_FROM_CLASS_A(T)) //See if T is a pointer to a class derived from class A arg->A_Function(); else if(DERIVED_FROM_CLASS_B(T)) //See if T derives from class B arg.B_Function(); else if(IS_TEMPLATE_CLASS_C(T)) //See if T is class C<U> where U could be anything arg.C_Function(); else if(IS_POD(T)) //See if T is a POD type //Do something with a POD type else //Do something else because none of the above rules apply } Is something like this possible? Thank you.
This is certainly possible; you just have to be careful to ensure that all of the branches are mutually exclusive, otherwise you'll end up with an ambiguity. Take a look at Boost Type Traits and Boost Enable If, which are the two best tools for supporting this. Boost ICE (which stands for Integral Constant Expression) can be used to combine multiple type traits to help you to do more complex type matching (and to ensure that your overloads are mutually exclusive. This can be somewhat complicated and convoluted, so here's a relatively straightforward example. Say you have a class hierarchy: struct Base { }; struct Derived : Base { }; and you want to call one overload of a function foo for Base, and another overload for any class derived from Base. A first attempt might look like: #include <boost/type_traits.hpp> #include <boost/utility/enable_if.hpp> using namespace boost; using namespace boost::type_traits; template <typename T> typename enable_if<is_same<Base, T>, void>::type foo(const T&) { } template <typename T> typename enable_if<is_base_of<Base, T>, void>::type foo(const T&) { } However, is_base_of returns true if T is the base class, so if you attempt to call foo(Base()), there is an ambiguity because both function templates match. We can resolve this by using a combination of the type traits and using the Boost ICE helpers: template <typename T> typename enable_if<is_same<Base, T>, void>::type foo(const T&) { } template <typename T> typename enable_if< ice_and< is_base_of<Base, T>::value, ice_not<is_same<Base, T>::value>::value >, void>::type foo(const T&) { } These overloads are mutually exclusive, and they ensure there is no ambiguity. Some of your examples are not supported (namely, HAS_MEMBER_FUNCTION_X; I'm not sure about IS_TEMPLATE_CLASS_C--depending on what you want to do with it you might be able to make something work), but in general this is possible.
2,718,689
2,718,694
C++ Vector of vectors is messing with me
If I put this code in a .cpp file and run it, it runs just fine: #include <iostream> #include <vector> #include <string> using namespace std; typedef vector<int> row; typedef vector<row> myMatrix; void main() { //cout << endl << "test" << endl; myMatrix mat(2,2); mat[0][1] = 2; cout << endl << mat[0][1] << endl; } But, if I make a .h and a .cpp file with the .h file like this, it gives me boatloads of errors. #ifndef _grid_ #define _grid_ #include<iostream> #include<vector> #include<string> using namespace std; typedef vector<int> row; typedef vector<row> myMatrix; class grid { public: grid(); ~grid(); int getElement(unsigned int ri, unsigned int ci); bool setElement(unsigned int ri, unsigned int ci, unsigned int value); private: myMatrix sudoku_(9,9); }; #endif These are some of the errors I get: warning C4091: 'typedef ' : ignored on left of 'int' when no variable is declared error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
You need to qualify vector as std::vector. It works in the .cpp file because you use using namespace std; (do not use using namespace in a header file). Furthermore, your declaration of the member variable is incorrect. It should just be: myMatrix sudoku_; If you want to set its dimensions, you need to do so in the constructor.
2,718,724
2,718,729
Operator overload for [] operator
Why would you need to overload the [] operator? I have never come across a practical scenario where this was necessary. Can somebody tell me a practical use case for this.
Err.. std::vector<t>, std::basic_string<t>, std::map<k, v>, and std::deque<t> ? I used this for a class representing a registry key, where operator[] returned an object representing a registry value with the string between []s. See also, the Spirit Parser Framework, which uses [] for semantic actions.
2,718,779
2,718,813
Correct Exceptions in C++
I am just learning how to handle errors in my C++ code. I wrote this example that looks for a text file called some file, and if its not found will throw an exception. #include <iostream> #include <fstream> using namespace std; int main() { int array[90]; try { ifstream file; file.open("somefile.txt"); if(!file.good()) throw 56; } catch(int e) { cout<<"Error number "<<e<<endl; } return 0; } Now I have two questions. First I would like to know if I am using Exceptions correctly. Second, (assuming the first is true) what is the benefit to using them vs an If else statement?
"Correctly" is a value judgment, but (unlike other classes) there's a major benefit from exceptions classes being a monolithic hierarchy, so I'd generally advise throwing something derived from std::exception, not simply an int. Second, it's open to question whether an incorrect file name is sufficiently unexpected to qualify as a good reason to throw an exception at all. As to benefits vs. an if/else statement: there are a couple. First, exceptions let you segregate the code that deals with errors, so the main idea and readability of the code don't get lost in a maze of error handling. Second, when you have several layers of code between throwing and catching the exception, the code that throws the exception may not know how it should really be handled. Your code, for example, uses std::cout to report the problem -- but most such code would report errors on std::cerr instead. You can change from one to the other without any change to the code that tried to open the file (which might be deep in a library, and have no clue of which should be used for this application -- and might be used in an application where both are wrong, and MessageBox was preferred).
2,718,815
2,718,847
returning reference to a vector from a method and using its public members
I have a vector t_vec that stores references to instances of class Too. The code is shown below. In the main , I have a vector t_vec_2 which has the same memory address as B::t_vec. But when I try to access t_vec_2[0].val1 it gives error val1 not declared. Could you please point out what is wrong? Also, if you know of a better way to return a vector from a method, please let me know! Thanks in advance. class Too { public: Too(); ~Too(){}; int val1; }; Too::Too(){ val1 = 10; }; class B { public: vector<Too*> t_vec; Too* t1; vector<Too*>& get_tvec(); B(){t1 = new Too();}; ~B(){delete t1;}; }; vector<Too*>& B::get_tvec(){ t_vec.push_back(t1); return t_vec; } int main(){ B b; b = B(); vector<Too*>& t_vec_2 = b.get_tvec(); // Getting error std::cout << "\n val1 = " << t_vec_2[0].val1; return 0; }
You have 2 errors: The first was already said, you should write t_vec_2[0]->val1 instead of t_vec_2[0].val1 The second is the strange line b = B(); I think you should delete it. The error occurs because right part B() is gonna be delete just after it is created. So you don't get in the object b the 10 value as you want. Just delete this line and it'll be ok!
2,718,836
2,719,177
How to define an extern, C struct returning function in C++ using MSVC?
The following source file will not compile with the MSVC compiler (v15.00.30729.01): /* stest.c */ #ifdef __cplusplus extern "C" { #endif struct Test; /* NB: This may be extern when imported by another module. */ struct Test make_Test(int x); struct Test { int x; }; struct Test make_Test(int x) { struct Test r; r.x = x; return r; } #ifdef __cplusplus } #endif Compiling with cl /c /Tpstest.c produces the following error: stest.c(8) : error C2526: 'make_Test' : C linkage function cannot return C++ class 'Test' stest.c(6) : see declaration of 'Test' Compiling without /Tp (which tells cl to treat the file as C++) works fine. The file also compiles fine in DigitalMars C and GCC (from mingw) in both C and C++ modes. I also used -ansi -pedantic -Wall with GCC and it had no complaints. For reasons I will go into below, we need to compile this file as C++ for MSVC (not for the others), but with functions being compiled as C. In essence, we want a normal C compiler... except for about six lines. Is there a switch or attribute or something I can add that will allow this to work? The code in question (though not the above; that's just a reduced example) is being produced by a code generator. As part of this, we need to be able to generate floating point nans and infinities as constants (long story), meaning we have to compile with MSVC in C++ mode in order to actually do this. We only found one solution that works, and it only works in C++ mode. We're wrapping the code in extern "C" {...} because we want to control the mangling and calling convention so that we can interface with existing C code. ... also because I trust C++ compilers about as far as I could throw a smallish department store. I also tried wrapping just the reinterpret_cast line in extern "C++" {...}, but of course that doesn't work. Pity. There is a potential solution I found which requires reordering the declarations such that the full struct definition comes before the function foward decl., but this is very inconvenient due to the way the codegen is performed, so I'd really like to avoid having to go down that road if I can.
This is an interesting question. As you say, compiling the code as C code rightly produces no error. And only MSVC seems to have trouble with it when compiled as C++ code. Since other C++ compilers don't have a problem with the code, this might be a bug in MSVC, but I can see how MSVC might have a rationale for this error. When the C++ compiler hits the line: struct Test; That's an incomplete declaration of struct Test - the compiler doesn't know if the complete definition of struct Test will contain C++ specific items (virtual functions, inheritance, etc). Note that types in an extern "C" block can still use all C++ facilities; the extern "C" language linkage specification applies only to "function types of all function declarators, function names, and variable names introduced by the declaration(s)" (7.5/4 "Linkage specifications"). So I could see how when MSVC's C++ compiler comes across an extern "C" function that's returning an incomplete type, it might decide that it needs to return an error at that point in case the type turns out to not be a plain C-style POD type. The C++ standard does say (7.5/9 "Linkage specifications"): Linkage from C++ to objects defined in other languages and to objects defined in C++ from other languages is implementation-defined and language-dependent. Only where the object layout strategies of two language implementations are similar enough can such linkage be achieved. So MSVC might have some leeway (standards-wise) if it has a reason to not permit extern "C" functions from returning non-POD objects, though I'm not sure why MSVC would have a problem when other Windows compilers don't. If anyone knows details (or if they know I'm just plain off-base here), I'd appreciate a note. Not that any of this this helps you - it's just my guess at a rationale. Without knowing more about your codegen process and how you might be able to influence it, I'm not sure what decent options you might have - maybe a post-processing of the generated files to split out the stuff that needs to be compiled as C (or rearranges the declarations). But I can imagine that that might be a nightmare to get working and especially to maintain.
2,718,918
2,718,937
Char* vs std::string
Possible Duplicate: C++ char* vs std::string Is there any advantage to using char*'s instead of std::string? I know char*'s are usually defined on the stack, so we know exactly how much memory we'll use, is this actually a good argument for their use? Or is std::string better in every way?
If you're writing in C++ then std::string will be better in most cases you'll encounter. Instead, a few cases when you might want to use char*'s: -Compatibility with old C code (although std::string's c_str() method handles most of this) -To conserve memory (std::string will likely have more overhead) -Cases where you want to make sure you know where the memory is at, such as network code or shared memory
2,719,136
2,719,155
overloading "<<" with a struct (no class) cout style
I have a struct that I'd like to output using either 'std::cout' or some other output stream. Is this possible without using classes? Thanks #include <iostream> #include <fstream> template <typename T> struct point{ T x; T y; }; template <typename T> std::ostream& dump(std::ostream &o,point<T> p) const{ o<<"x: " << p.x <<"\ty: " << p.y <<std::endl; } template<typename T> std::ostream& operator << (std::ostream &o,const point<T> &a){ return dump(o,a); } int main(){ point<double> p; p.x=0.1; p.y=0.3; dump(std::cout,p); std::cout << p ;//how? return 0; } I tried different syntax' but I cant seem to make it work.
Perhaps it's a copy-paste error, but there are just a few things wrong. Firstly, free-functions cannot be const, yet you have marked dump as such. The second error is that dump does not return a value, which is also easily remedied. Fix those and it should work: template <typename T> // note, might as well take p as const-reference std::ostream& dump(std::ostream &o, const point<T>& p) { return o << "x: " << p.x << "\ty: " << p.y << std::endl; }
2,719,142
2,719,236
Splitting a C++ class into files now won't compile
I am teaching myself to write classes in C++ but can't seem to get the compilation to go through. If you can help me figure out not just how, but why, it would be greatly appreciated. Thank you in advance! Here are my three files: make_pmt.C #include <iostream> #include "pmt.h" using namespace std; int main() { CPMT *pmt = new CPMT; pmt->SetVoltage(900); pmt->SetGain(2e6); double voltage = pmt->GetVoltage(); double gain= pmt->GetGain(); cout << "The voltage is " << voltage << " and the gain is " << gain << "." <<endl; return 0; } pmt.C #include "pmt.h" using namespace std; class CPMT { double gain, voltage; public: double GetGain() {return gain;} double GetVoltage() {return voltage;} void SetGain(double g) {gain=g;} void SetVoltage(double v) {voltage=v;} }; pmt.h #ifndef PMT_H #define PMT_H 1 using namespace std; class CPMT { double gain, voltage; public: double GetGain(); double GetVoltage(); void SetGain(double g); void SetVoltage(double v); }; #endif And for reference, I get a linker error (right?): Undefined symbols: "CPMT::GetVoltage()", referenced from: _main in ccoYuMbH.o "CPMT::GetGain()", referenced from: _main in ccoYuMbH.o "CPMT::SetVoltage(double)", referenced from: _main in ccoYuMbH.o "CPMT::SetGain(double)", referenced from: _main in ccoYuMbH.o ld: symbol(s) not found collect2: ld returned 1 exit status
First some taxonomy. This class CPMT { public: double GetGain(); // ... }; is defining a class without also defining the member functions. This class CPMT { public: double GetGain() {return gain;} // ... }; is defining the same class, with also defining its member functions (implicitly) inline. This double CPMT::GetGain() {return gain;} // ... is defining the member functions (not inline). Now, if you want to separate implementation from interface, your header needs to define the class, while your implementation file needs to define its member functions. So the pure class definition class CPMT { public: double GetGain(); //... }; goes into the header file and the implementation double CPMT::GetGain() {return gain;} // ... goes into the implementation file - except for those member functions you want to implement inline. Since inline asks the compiler to substitute a function's implementation for every call to it, the implementation must be present where the function is called. That's why the implementations of inlined functions must be in header files. There are two ways to inline a member function. One is to define it within its class's definition class CPMT { public: double GetGain() {return gain;} // ... }; which implicitly makes it inline. The other is to explicitly inline it class CPMT { public: double GetGain(); //... }; inline double CPMT::GetGain() {return gain;} // ... In both cases the implementation must be in the header file.
2,719,204
2,719,617
Make conversion to a native type explicit in C++
I'm trying to write a class that implements 64-bit ints for a compiler that doesn't support long long, to be used in existing code. Basically, I should be able to have a typedef somewhere that selects whether I want to use long long or my class, and everything else should compile and work. So, I obviously need conversion constructors from int, long, etc., and the respective conversion operators (casts) to those types. This seems to cause errors with arithmetic operators. With native types, the compiler "knows" that when operator*(int, char) is called, it should promote the char to int and call operator*(int, int) (rather than casting the int to char, for example). In my case it gets confused between the various built-in operators and the ones I created. It seems to me like if I could flag the conversion operators as explicit somehow, that it would solve the issue, but as far as I can tell the explicit keyword is only for constructors (and I can't make constructors for built-in types). So is there any way of marking the casts as explicit? Or am I barking up the wrong tree here and there's another way of solving this? Or maybe I'm just doing something else wrong... EDIT: A little clarification on what I want to do: I have a project that uses 64-bit ('long long`) operations in many places, and I am trying to port it to a platform that doesn't have built-in support for 64-bit variables/operations. Even though I have the source for the project, I would really prefer not to have to go over the thousands of places where built-in operators and C-style casts are and change them around. As for the code itself, the project has the following definitions and kinds of code: typedef long long i64; // I would like to only have to change this to use my class instead of "long long" int a; unsigned b; int c = ((i64)a*b)>>32; As for the class implementation, I have the following: class Long64 { public: Long64(); Long64(const Long64&); Long64(int); Long64(long); Long64(unsigned int); Long64(unsigned long); operator int() const; operator long() const; operator unsigned int() const; operator unsigned long() const; friend Long64 operator*(int l, const Long64& r); friend Long64 operator*(const Long64& l, int r); friend Long64 operator*(long l, const Long64& r); friend Long64 operator*(const Long64& l, long r); }
To avoid the compiler to be confused, you will help it by defining the combination of your class and the built-in types for all the arithmetic operator. For example for operator+, you will need to define + the unsigned ones MyClass operator+(char, MyClass const&); MyClass operator+(MyClass const&, char); MyClass operator+(short, MyClass const&); MyClass operator+(MyClass const&,short); MyClass operator+(MyClass const&,int); the compiler will prefer overloads that don't need to use conversion operators. Of course all these methods will use the overload MyClass operator+(MyClass const&,MyClass const&); by explicitly converting one of the parameters to your class MyClass MyClass operator+(char c, MyClass const& m) { return MyClass(c)+m;} This is a little bit cumbersome, I know, but it should avoid the conflicts.
2,719,226
2,722,489
How to generate a VBR video from stream of YUV images?
My hardware (video capture card) gives me the images in YV12 (YUV 420) format and I am trying to generate a video from it. I am using C++ under windows and I would like to generate a mpeg-4 VBR video from that stream but I dont know where I should start... (I need it to be VBR because it is a security camera and there will be a lot of repeated frames) Is there any library that does something like this?
ffmpeg will do this for you. Check out this part of the documentation where they talk about encoding raw YUV 420P frames. You can use ffmpeg's built-in mpeg 4 encoder, or it also allows you to interface with other libraries like xvid and x264. The easiest way to handle this would be to just use the command line ffmpeg executable and just call it from your C++ program. Another option is to use libavformat and libavcodec (ffmpeg libraries). This will require more work, but give you more control over the process (for instance, if you need to do any processing of the video data).
2,719,641
2,719,660
Can there be two public section in a class? If yes then why ? And in which circumstances we do so?
There is something bugging me about classes. For example class A { public: A() { ..... ..... } void cleanup() { .... .... .... } public: UINT a; ULONG b; }; In the above example there are two public section. In the first section I am defining a constructor and a method and in the second section I am declaring data members. Is the above class i.e. A correct. Can we do that? If yes then why is that needed and in what circumstances should we use it? Since we can do the entire thing in one section then why are there two sections?
Access qualifiers simply apply to the code that follows until the next qualifier. There is no restriction on the number or order of such qualifiers. It is generally not necessary to repeat the same access qualifier in a class, and doing so is likely to confuse the reader. They also may have an effect on the layout of a class, since data members following the same qualifier must be laid out in the order they are declared, but there is no such restriction between qualifiers.
2,719,741
2,816,930
Advice when using COM Object/CComPtr and the STL
I am doing some COM related things with directshow such as: typedef CComPtr<IBaseFilter> AutoIBaseFilterPtr; map<CString, AutoIBaseFilterPtr> _filterMap; To store a list of directShow related com objects and their friendly name. After finding this article (See:Problem 2) on how changes in VC10 compiler might effect previously OK code, I am wondering if there are any more things to watch out for when mixing the STL and CComPtr or prehaps just mixing the STL and COM in general. Any tips would be greatly appreciated, thanks
The only slight thing I can think of that hasn't been mentioned is that CAdapt is required for CComBSTR as well as CComPtr, because it overloads operator& too. In fact, it is overloading operator& that makes CAdapt necessary, as many STL containers require that taking the address of something X returns a pointer to said X.
2,719,832
2,719,880
Why is overloading operator&() prohibited for classes stored in STL containers?
Suddenly in this article ("problem 2") I see a statement that C++ Standard prohibits using STL containers for storing elemants of class if that class has an overloaded operator&(). Having overloaded operator&() can indeed be problematic, but looks like a default "address-of" operator can be used easily through a set of dirty-looking casts that are used in boost::addressof() and are believed to be portable and standard-compilant. Why is having an overloaded operator&() prohibited for classes stored in STL containers while the boost::addressof() workaround exists?
Without having looked at the links, I suppose the tricks in boost::addressof() were invented well after the requirement to not to overload unary prefix & for objects to be held in containers of the std lib. I vaguely remember Pete Becker (then working for Dinkumware on their standard library implementation) once stating that everyone who overloads the address-of operator and expects their standard library implementation still to work should be punished by having to implement a standard library which does this.
2,719,922
2,720,223
How to install the program depending on libstdc++ library
My program is written in C++, using GCC on Ubuntu 9.10 64 bit. If depends on /usr/lib64/libstdc++.so.6 which actually points to /usr/lib64/libstdc++.so.6.0.13. Now I copy this program to virgin Ubuntu 7.04 system and try to run it. It doesn't run, as expected. Then I add to the program directory the following files: libstdc++.so.6.0.13 libstdc++.so.6 (links to libstdc++.so.6.0.13) Execute command: LD_LIBRARY_PATH=. ./myprogram Now everything is OK. The question: how can I write installation script for such program? myprogram file itself should be placed to /usr/local/bin. What can I do with dependencies? For example, on destination computer, /usr/lib64/libstdc++.so.6 link points to /usr/lib64/libstdc++.so.6.0.8. What can I do with this? Note: the program is closed-source, I cannot provide source code and makefile.
If you're working on Ubuntu, making a .deb (Debian Package) seems to way to go. Here is a link to get you started. Your package will state it depends on some other packages (typically the packages that includes libstdc++.so.6.0.13 - i guess the package name is something like libstdc++) and dependencies will be installed when you install your own package using dpkg -i <yourpackage>.deb. Afterwards, you'll be able to uninstall it using dpkg -r <yourpackage>. Anyway, never ship such standards files with your own archive. Dependencies exists for this exact purpose. Hope it helps.
2,719,984
2,719,996
vector related memory allocation question
I am encountering the following bug. I have a class Foo . Instances of this class are stored in a std::vector vec of class B. in class Foo, I am creating an instance of class A by allocating memory using new and deleting that object in ~Foo(). the code compiles, but I get a crash at the runtime. If I disable delete my_a from desstructor of class Foo. The code runs fine (but there is going to be a memory leak). Could someone please explain what is going wrong here and suggest a fix? thank you! class A{ public: A(int val); ~A(){}; int val_a; }; A::A(int val){ val_a = val; }; class Foo { public: Foo(); ~Foo(); void createA(); A* my_a; }; Foo::Foo(){ createA(); }; void Foo::createA(){ my_a = new A(20); }; Foo::~Foo(){ delete my_a; }; class B { public: vector<Foo> vec; void createFoo(); B(){}; ~B(){}; }; void B::createFoo(){ vec.push_back(Foo()); }; int main(){ B b; int i =0; for (i = 0; i < 5; i ++){ std::cout<<"\n creating Foo"; b.createFoo(); std::cout<<"\n Foo created"; } std::cout<<"\nDone with Foo creation"; std::cout << "\nPress RETURN to continue..."; std::cin.get(); return 0; }
You need to implement a copy constructor and an assignment operator for Foo. Whenever you find you need a destructor, you alnmost certainly need these two as well. They are used in many places, specifically for putting objects into Standard Library containers. The copy constructor should look like this: Foo :: Foo( const Foo & f ) : my_a( new A( * f.my_a ) ) { } and the assignment operator: Foo & Foo :: operator=( const Foo & f ) { delete my_a; my_a = new A( * f.my_a ); return * this; } Or better still, don't create the A instance in the Foo class dynamically: class Foo { public: Foo(); ~Foo(); void createA(); A my_a; }; Foo::Foo() : my_a( 20 ) { };
2,720,018
2,720,053
Using Qt's XML library for simple operation
I basically want to use the XML parser from Qt in my existing project. I have only used Qt once before, and that was with Qt Designer, and I am not having much luck finding anything on Google about how to just use the XML library. I have downloaded a web page that has one large list, and I want to parse it and add each list item to a c++ list. I found this sample code on Ubuntu forums... http://www.uluga.ubuntuforums.org/showpost.php?p=9112973&postcount=6 I want to use that except I need to know what exactly I need to add to the project to get access to it. One other small question is QDomDocument seems to be for files (makes sense) but I have the XML in a string. What part of the XML library works for contents of a string?
The following code should give you a quick view of what to do with Qt XML features for what you need. #include <list> #include <QDomDocument> #include <QFile> int main() { QString filename("myfile.xml"); std::list<QString> result; int errorLine, errorColumn; QString errorMsg; QFile modelFile(filename); QDomDocument document; if (!document.setContent(&modelFile, &errorMsg, &errorLine, &errorColumn)) { QString error("Syntax error line %1, column %2:\n%3"); error = error .arg(errorLine) .arg(errorColumn) .arg(errorMsg); return false; } QDomElement rootElement = document.firstChild().toElement(); for(QDomNode node = rootElement.firstChild(); !node .isNull(); node = node .nextSibling()) { QDomElement element = node.toElement(); result.push_back(element.tagName()); } return 0; } UPDATE I believe you only need core Qt library as well as XML library.
2,720,181
2,720,593
How to make some simple GUI controls?
I need to make a DirectX or OpenGL app and i will need a custom GUI for that. I think a button, a input text box, a list box (that will need a scroll bar as there will be more items that can fit on the screen) and a slider control will be enough. I know about CeGUI framework but i just don't like it, way too many XML files for my taste. My question is where should i start in learning how to do this custom GUI controls, are there any tutorial available or any material that could get me started? I haven't done a GUI contol myself before.
A little bit of googling turns up the following: libnui Bram Stein's UI library GiGi ... and then some.
2,720,259
2,720,446
Using MSADO15.DLL and C++ with MinGW/GCC on Windows Vista
INTRODUCTION Hi, I am very new to C++, is my 1st statement. I have started initially with VC++ 2008 Express, I've notice that GCC becomes kind of standard so I am trying to make the right steps event from the beginning. I have written a piece of code that connects to MSSQL Server via ADO, on VC++ it's working like a charm by importing MSADO15.dll: #import "msado15.dll" no_namespace rename("EOF", "EndOfFile") Because I am going to move from VC++ I was looking for an alternative (eventually multi-platform) IDE, so I stick (for this time) with Code::Block (I'm using last nightly buil, SVN 6181). As compiler I choose to use GCC 3.4.5 (ported via MinGW 5.1.6), under Vista. I was trying to compile a simple "hello world" application with GCC that use/import the same msado15.dll (#import "c:\Program Files\Common Files\System\ADO\msado15.dll" no_namespace rename("EOF", "EndOfFile")) and I was surprised to see a lot of compile-time errors. I was expected that the #import compiler's directive will generate a library from "msado15.dll" so it can link to it later (link-edit time or whatever). Instead it was trying to read it as a normal file (like a header file,if you like) because it was trying to interprete each line in the DLL (which has a MZ signature): Example: Compiling: main.cpp E:\MyPath\main.cpp:2:64: warning: extra tokens at end of #import directive In file included from E:\MyPath\main.cpp:2: c:\Program Files\Common Files\System\ADO\msado15.dll:1: error: stray '\144' in program In file included from E:\MyPath\main.cpp:2: c:\Program Files\Common Files\System\ADO\msado15.dll:1:4: warning: null character(s) ignored c:\Program Files\Common Files\System\ADO\msado15.dll:1: error: stray '\3' in program c:\Program Files\Common Files\System\ADO\msado15.dll:1:6: warning: null character(s) ignored c:\Program Files\Common Files\System\ADO\msado15.dll:1: error: stray '\4' in program ... and so on. MY QUESTION Well, it is obvious that under this version of GCC the #import directive does not do the expected job (perhaps #import is not supported anymore by GCC), so finally my question: how to use the ADO to access MSSQL database on a C++ program compiled with GCC (v3.4.5)?
GCC and MSVC use #import for different things. In GCC, #import is an objective-c variant of #include that only includes the header file once. In MSVC, #import triggers a Microsoft extension that builds a smart pointer implementation and header files from a COM type library. In GCC you are going to have to import the COM object the old fashioned way. Find the existing interface definitions or use a tool like OleSpy to generate the definitions from the tlb.
2,720,495
2,720,991
Static variable not initialized
I've got a strange problem with a static variable that is obviously not initialized as it should be. I have a huge project that runs with Windows and Linux. As the Linux developer doesn't have this problem I would suggest that this is some kind of wired Visual Studio stuff. Header file class MyClass { // some other stuff here ... private: static AnotherClass* const Default_; }; CPP file AnotherClass* const MyClass::Default_(new AnotherClass("")); MyClass(AnotherClass* const var) { assert(Default_); ... } Problem is that Default_is always NULL. I also tried a breakpoint at the initialization of that variable but I cannot catch it. There is a similar problem in another class. CPP file std::string const MyClass::MyString_ ("someText"); MyClass::MyClass() { assert(MyString_ != ""); ... } In this case MyString_is always empty. So again not initialized. Does anyone have an idea about that? Is this a Visual Studio settings problem? Cheers Simon Edit: I also came across the static initialization fiasco. But I'm not sure if that could be the problem because there are no problems with the Linux compiler. Shouldn't the compiler react the same way in this case?
I suggest you use static member function with static variable and not static variable itself: class MyClass { // some other stuff here ... private: static AnotherClass* const getAnotherClass(); }; AnotherClass *const MyClass::getAnotherClass() { static AnotherClass *const p = new AnotherClass(""); return(p); } The standard guarantees that p is initialized once when the function is called for the first time, so you will always get properly initialized object (unless you've already exhausted memory or you constructor threw). Please note - this may or may not be thread safe (depends on your compiler really). And yet another note - now you have to live with "memory leak" as it is really next to impossible to decide when to destroy the object and you have NO WAY to reset p to NULL.
2,720,752
2,720,803
How does large text file viewer work? How to build a large text reader
how does large text file viewer work? I'm assuming that: Threading is used to handle the file The TextBox is updated line by line Effective memory handling is used Are these assumptions correct? if someone were to develop their own, what are the mustsand don'ts? I'm looking to implement one using a DataGrid instead of a TextBox I'm comfortable with C++ and python. I'll probably use QT/PyQT EDIT The files, I have are usually between 1.5 to 2 GB. I'm looking at editing and viewing these files
I believe that the trick is not loading the entire file into memory, but using seek and such to just load the part which is viewed (possibly with a block before and after to handle a bit of scrolling). Perhaps even using memory-mapped buffers, though I have no experience with those. Do realize that modifying a large file (fast) is different from just viewing it. You might need to copy the gigabytes of data surrounding the edit to a new file, which may be slow.
2,720,988
2,720,999
Why this function overloading is not working?
class CConfFile { public: CConfFile(const std::string &FileName); ~CConfFile(); ... std::string GetString(const std::string &Section, const std::string &Key); void GetString(const std::string &Section, const std::string &Key, char *Buffer, unsigned int BufferSize); ... } string CConfFile::GetString(const string &Section, const string &Key) { return GetKeyValue(Section, Key); } void GetString(const string &Section, const string &Key, char *Buffer, unsigned int BufferSize) { string Str = GetString(Section, Key); // *** ERROR *** strncpy(Buffer, Str.c_str(), Str.size()); } Why do I get an error too few arguments to function ‘void GetString(const std::string&, const std::string&, char*, unsigned int)' at the second function ? Thanks
Because the CConFile::GetString() is, as the name suggest, a class member function, that is not accessible the way you call it in the second function. The other function you're declaring, GetString(), is a global one. You just forgot to add CConFile:: to the second function...
2,720,989
2,721,018
How to set text editable in GtkEntry
Pretty straight forward question, I have a GtkEntry widget that I want to set to be editable. I know the function I should use is: gtk_editable_set_editable But I don't know how to make it take a GtkEntry widget as an argument Here is the code I'm using: GtkWidget *TextEntry; TextEntry = gtk_entry_new(); gtk_entry_set_visibility(GTK_ENTRY(TextEntry), TRUE); gtk_entry_set_editable(GTK_ENTRY(TextEntry), TRUE); gtk_entry_set_overwrite_mode(GTK_ENTRY(TextEntry), TRUE); gtk_widget_set_can_focus(GTK_WIDGET(TextEntry), TRUE); gtk_widget_grab_focus(TextEntry); panel_applet_request_focus(applet, 10); gtk_container_add (GTK_CONTAINER (applet), TextEntry); gtk_widget_show_all (GTK_WIDGET (applet)); So far as getting keyboard focus, I think I need the panel_applet_request_focus () function. It requires that i pass it the applet in question and the timestamp of the event triggering the window focus I'm not sure what to put in for the timestamp. I compiled the code as above and I still can't get keyboard focus when I click the applet.
Do the following: GtkWidget* entry = gtk_entry_new(); gtk_entry_set_editable(GTK_ENTRY(entry), TRUE); Welcome to the world of GObject :) Note that if you were using gtk_editable, you need to do: gtk_editable_set_editable(GTK_EDITABLE(entry), TRUE);
2,721,128
2,721,158
Why do I need to call new?
Possible Duplicates: When to use “new” and when not to, in C++? When should I use the new keyword in C++? It seems like I could program something without ever using the word new, and I would never have to worry about deleting anything either, so why should I ever call it? From what I understand, it's because I would run out of stack memory. Is this correct? I guess my main question is, when should I call new?
It's a matter of object lifetime: if you stack-allocate your objects, the objects destructors will be called when these objects go out of scope (say, at the end of the method). This means that if you pass these objects out of the method that created them, you'll find yourself with pointers to memory that could be overwritten at any time.
2,721,244
2,721,836
What is the fastest way to calculate the number of bits needed to store a number
I'm trying to optimize some bit packing and unpacking routines. In order to do the packing I need to calculate the number of bits needed to store integer values. Here is the current code. if (n == -1) return 32; if (n == 0) return 1; int r = 0; while (n) { ++r; n >>= 1; } return r;
You're looking to determine the integer log base 2 of a number (the l=highest bit set). Sean Anderson's "Bit Twiddling Hacks" page has several methods ranging from the obvious counting bits in a loop to versions that use table lookup. Note that most of the methods demonstrated will need to be modified a bit to work with 64-bit ints if that kind of portability is important to you. http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious Just make sure that any shifting you're using to work out the highest bit set needs to be done' on an unsigned version of the number since a compiler implementation might or might not sign extend the >> operation on a signed value.
2,721,263
2,721,471
Pointer-Safe Objects?
Would it be smart to have a vector in an object with a list of pointers that point to it? This way when the object is deleted, it could delete all the pointers pointing to it to prevent a null-pointer exception?
If your ultimate goal is to detect when an object is freed from users of the object the best bet is to use a weak pointer semantic. There an implementation in the Boost Smart Pointer library (see weak_ptr). It solves the problem you describe by reversing the reference graph you describe. It has the pointers reference a single common counter instance which when the originator deletes the object it sets to zero. Hence because all the weak_ptr references point to the single counter they all see the change immediately and hence you can tell when the object goes away.
2,721,315
2,721,357
Dictionary/HashTable Object in C++?
I'm looking for a HashTable or Dictionary implementation in C++ that has similar functionality to the one in C#? Does the STL contain an object like this and how would I use it?
Actually, to be exactly the same as .NET's Dictionary/Hashtable, what you want is hash_map or unordered_map (std::map is implemented as a binary tree), hash_map is an extension to the SC++L. Most compilers that I know of come with hash_map, though, and boost obviously has unordered_map until C++0x is available in all compilers, so you should just be able to use it without trouble.
2,721,421
2,721,499
How to add/design callback function
How do I setup/register a callback function, in C++, to call a function when there is data to be read from a queue? Edit 1: Using Neil's answer for a complete answer (in header file): #include <vector.h> class QueueListener { public: virtual void DataReady(class MyQueue *q) = 0; virtual ~QueueListener() {} }; class MyQueue { public: void Add (int x) { theQueue.push_back(x); for (int i = 0; i < theCallBacks.size(); i++) { theCallBacks[i]->DataReady(this); } } void Register (QueueListener *ql) { theCallBacks.push_back(ql); } private: vector <QueueListener *> theCallBacks; vector <int> theQueue; }; class MyListener : public QueueListener { public: virtual ~MyListener () { printf("MyListener destructor!"); } MyListener(MyQueue *q); virtual void DataReady(class MyQueue *p); }; And the registering: #include "File1.h" MyListener::MyListener(MyQueue *q) { q->Register(this); } void MyListener::DataReady(class MyQueue *p) { Sleep(500); } Then the calls: void __fastcall TForm1::Button1Click(TObject *Sender) { MyQueue *q = new MyQueue(); MyListener ml(q); q->Add(1); }
In outline, create a QueueListener base class: class QueueListener { public: virtual void DataReady( class MyQueue & q ) = 0; virtual ~QueueListener() {} }; and a queue class (make this queue of integers as example: class MyQueue { public: void Add( int x ) { theQueue.push_back( x ); for ( int i = 0; i < theCallBacks.size(); i++ ) { theCallBacks[i]->DataReady( * this ); } } void Register( QueueListener * ql ) { theCallBacks.push_back( ql ); } private: vector <QueueListener *> theCallBacks; SomeQueueType <int> theQueue; }; You derive the classes that want to be called back from QueueListener and implement the DataReady function. You then register instances of the derived class with your queue instance.
2,721,647
2,721,923
How can I make the compiler create the default constructors in C++?
Is there a way to make the compiler create the default constructors even if I provide an explicit constructor of my own? Sometimes I find them very useful, and find it a waste of time to write e.g. the copy constructor, especially for large classes.
The copy constructor is provided whether you define any other constructors or not. As long as you don't declare a copy constructor, you get one. The no-arg constructor is only provided if you declare no constructors. So you don't have a problem unless you want a no-arg constructor, but consider it a waste of time writing one. IIRC, C++0x has a way of delegating construction to another constructor. I can't remember the details, but it would allow you to define a no-arg constructor by specifying another constructor, plus the argument(s) to pass to it. Might save typing some data member initializers in some cases. But the default no-arg constructor wouldn't have provided those initializers either.
2,721,648
2,721,698
C++ Unary - Operator Overload Won't Compile
I am attempting to create an overloaded unary - operator but can't get the code to compile. A cut-down version of the code is as follows:- class frag { public: frag myfunc (frag oper1, frag oper2); frag myfunc2 (frag oper1, frag oper2); friend frag operator + (frag &oper1, frag &oper2); frag operator - () { frag f; f.element = -element; return f; } private: int element; }; frag myfunc (frag oper1, frag oper2) { return oper1 + -oper2; } frag myfunc2 (frag oper1, frag oper2) { return oper1 + oper2; } frag operator+ (frag &oper1, frag &oper2) { frag innerfrag; innerfrag.element = oper1.element + oper2.element; return innerfrag; } The compiler reports... /home/brian/Desktop/frag.hpp: In function ‘frag myfunc(frag, frag)’: /home/brian/Desktop/frag.hpp:41: error: no match for ‘operator+’ in ‘oper1 + oper2.frag::operator-()’ /home/brian/Desktop/frag.hpp:16: note: candidates are: frag operator+(frag&, frag&) Could anyone suggest what I need to be doing here?
const-correctness This has to be frag operator+ (const frag &oper1, const frag &oper2); or else the operands can't be temporaries, such as the return value of operator- And unary minus should rather be: frag operator - () const; since it shouldn't modify the operand.
2,721,762
2,721,802
What are windows IPC methods
Question: I have a dll that I can load in another program. Now the dll has access to all data/functions in the other program. Which technology can I use that now an external program can send data/commands to that dll, to steer the other program, or get data from it ? I mean, in the past that meant DDE, I think that was back in Windows 3.11/95 times. What can I use today? Which one is easiest ? Which one is fastest?
Some common ones are: Named Pipes. Fairly easy to implement. Shared Memory. A little more work but may be a little bit faster (at least in my testing). Sockets. This is fairly simple and very portable but not as high performance. But it is sure nice if you suddenly want to be able to communicate with a process running on a different machine.
2,721,846
2,722,869
Alternative to c++ static virtual methods
In C++ is not possible to declare a static virtual function, neither cast a non-static function to a C style function pointer. Now, I have a plain ol' C SDK that uses function pointers heavily. I have to fill a structure with several function pointers. I was planning to use an abstract class with a bunch of static pure virtual methods, and redefine them in derived classes and fill the structure with them. It wasn't until then that I realized that static virtual are not allowed in C++. Also this C SDKs function signature doesn't have a userData param. Is there any good alternative? The best I can think of is defining some pure virtual methods GetFuncA(), GetFuncB(),... and some static members FuncA()/FuncB() in each derived class, which would be returned by the GetFuncX(). Then a function in the abstract class would call those functions to get the pointers and fill the structure. Edit Answering to John Dibling, it would be great to be able to do this: class Base { FillPointers() { myStruct.funA = myFunA; myStruct.funB = myFunB; ...} private: CStruct myStruct; static virtual myFunA(...) = 0; static virtual myFunB(...) = 0; }; class Derived1 : public Base { Derived1() { FillPointers(); } static virtual myFunA(...) {...}; static virtual myFunB(...) {...}; }; class Derived2 : public Base { Derived2() { FillPointers(); } static virtual myFunA(...) {...}; static virtual myFunB(...) {...}; }; int main() { Derived1 d1; Derived2 d2; // Now I have two objects with different functionality }
You can make Base be a class template that takes its function pointers from its template argument: extern "C" { struct CStruct { void (*funA)(int, char const*); int (*funB)(void); }; } template <typename T> class Base { public: CStruct myStruct; void FillPointers() { myStruct.funA = &T::myFunA; myStruct.funB = &T::myFunB; } Base() { FillPointers(); } }; Then, define your derived classes to descend from an instantiation of Base using each derived class as the template argument: class Derived1: public Base<Derived1> { public: static void myFunA(int, char const*) { } static int myFunB() { return 0; } }; class Derived2: public Base<Derived2> { public: static void myFunA(int, char const*) { } static int myFunB() { return 1; } }; int main() { Derived1 d1; d1.myStruct.funA(0, 0); d1.myStruct.funB(); Derived2 d2; d2.myStruct.funA(0, 0); d2.myStruct.funB(); } That technique is known as the curiously recurring template pattern. If you neglect to implement one of the functions in a derived class, or if you change the function signature, you'll get a compilation error, which is exactly what you'd expect to get if you neglected to implement one of the pure virtual functions from your original plan. The consequence of this technique, however, is that Derived1 and Derived2 do not have a common base class. The two instantiations of Base<> are not related in any way, as far as the type system is concerned. If you need them to be related, then you can introduce another class to serve as the base for the template, and then put the common things there: class RealBase { public: CStruct myStruct; }; template <typename T> class Base: public RealBase { // ... }; int main() RealBase* b; Derived1 d1; b = &d1; b->myStruct.funA(0, 0); b->myStruct.funB(); Derived2 d2; b = &d2; b->myStruct.funA(0, 0); b->myStruct.funB(); } Beware: Static member functions are not necessarily compatible with ordinary function pointers. In my experience, if the compiler accepts the assignment statements shown above, then you can at least be confident that they're compatible for that compiler. This code isn't portable, but if it works on all the platforms you need to support, then you might consider it "portable enough."
2,722,184
2,722,205
Problem with default member functions of class in C++ (constructor, destructor, operator=, copy constructor) (default ctor, dtor, copy ctor)
We know that compiler generates some member functions for user-defined class if that member functions are not defined but used, isn't it. So I have this kind of code: class AA { }; void main() { AA a; AA b(a); a = b; } This code works fine. I mean no compiler error. But the following code.... class AA { int member1; int member2; }; But this code gives an run time error, because variable "a" is used without being iniltialized!!! So my question is this: when we instantiate an int, it has a value. So why the default constructer doesn't work and by using those two int numbers initializes variable "a"?? EDIT: Platform: Win Vista, Compiler: Visual Studio 2008 compiler; Flags: Default
The compiler-synthesised default constructor calls the default constructors for all class members that have constructors. But integers don't have constructors, and so are not initialised. However, I find it hard to believe that this will cause a run-time error. To initialise those variables: class AA { public: AA() : member1(0), member2(0) {} private: int member1; int member2; };
2,722,222
2,722,265
Does it make a difference whether I put 'friend class xxxxx' in the public or private section?
class A1 { public: friend class B; } class A2 { private: friend class B; } Any difference?
No, access specificators have no effect on friend declaration.