Re: How to insert and retrive an object without default ctor from container?
The operator[] of std::map creates an object (using the default constructor) if none is found at the given key. Since this is undesirable here, use the find() member function of std::map instead.
C + C++ Compiler: MinGW port of GCC
Build + Version Control System: SCons + Bazaar
Re: How to insert and retrive an object without default ctor from container?
i tried the following:
Code:
mymap["test"]=mycppobj;
std::map<std::string,CPP_OBJECT>::iterator it=mymap.find("test");
std::pair<std::string,CPP_OBJECT> pair=*it;
CPP_OBJECT* t=pair.second(); //i still getting error : call of an object wihtout appropriate operator() or conversion functions to pointer-to-function type...
Re: How to insert and retrive an object without default ctor from container?
Originally Posted by mce
could you show me a simple working codes?
There are thousands of examples in books, on the Internet, etc. If you're going to use the container classes, you should have reference material ready to use instead of guessing what the code should be:
Re: How to insert and retrive an object without default ctor from container?
Originally Posted by mce
i tried the following:
Code:
mymap["test"]=mycppobj;
std::map<std::string,CPP_OBJECT>::iterator it=mymap.find("test");
std::pair<std::string,CPP_OBJECT> pair=*it;
CPP_OBJECT* t=pair.second(); //i still getting error : call of an object wihtout appropriate operator() or conversion functions to pointer-to-function type...
could you show me a simple working codes?
Almost right, but "second" is just a struct member variable, not a function, so it should be:
Code:
std::map<std::string,CPP_OBJECT>::iterator it=mymap.find("test");
std::pair<std::string,CPP_OBJECT> pair=*it;
CPP_OBJECT* t=pair.second;//No parenthesis here
----
Originally Posted by laserlight
It should be something like:
Code:
std::map<std::string,CPP_OBJECT>::iterator it = mymap.find("test");
if (it != mymap.end())
{
std::cout << *it << std::endl;
}
That won't work, "it" is an iterator to a key-value pair, that isn't streamable. it should be (if you wanted to print the pair):
Code:
std::map<std::string,CPP_OBJECT>::iterator it = mymap.find("test");
if (it != mymap.end())
{
std::cout << it->first << " " << it->second << std::endl;
}
Is your question related to IO?
Read this C++ FAQ LITE article at parashift by Marshall Cline. In particular points 1-6.
It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.
Bookmarks