Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over a std::map full of strings in C++

I have the following issue related to iterating over an associative array of strings defined using std::map.

-- snip -- class something  { //...    private:       std::map<std::string, std::string> table; //... } 

In the constructor I populate table with pairs of string keys associated to string data. Somewhere else I have a method toString that returns a string object that contains all the keys and associated data contained in the table object(as key=data format).

std::string something::toString()  {         std::map<std::string, std::string>::iterator iter;         std::string* strToReturn = new std::string("");          for (iter = table.begin(); iter != table.end(); iter++) {            strToReturn->append(iter->first());            strToReturn->append('=');            strToRetunr->append(iter->second());            //....         }        //... } 

When I'm trying to compile I get the following error:

error: "error: no match for call to ‘(std::basic_string<char,     std::char_traits<char>, std::allocator<char> >) ()’". 

Could somebody explain to me what is missing, what I'm doing wrong? I only found some discussion about a similar issue in the case of hash_map where the user has to define a hashing function to be able to use hash_map with std::string objects. Could be something similar also in my case?

like image 481
crazybyte Avatar asked Jun 30 '09 23:06

crazybyte


People also ask

Can we store string in map?

Maps are associative containers that store elements in a specific order. It stores elements in a combination of key values and mapped values. To insert the data in the map insert() function in the map is used.

Can you iterate through a Hashmap C++?

By using std::for and lambda function we can successfully iterate over all the elements of map.


1 Answers

Your main problem is that you are calling a method called first() in the iterator. What you are meant to do is use the property called first:

...append(iter->first) rather than ...append(iter->first()) 

As a matter of style, you shouldn't be using new to create that string.

std::string something::toString()  {         std::map<std::string, std::string>::iterator iter;         std::string strToReturn; //This is no longer on the heap          for (iter = table.begin(); iter != table.end(); ++iter) {            strToReturn.append(iter->first); //Not a method call            strToReturn.append("=");            strToReturn.append(iter->second);            //....            // Make sure you don't modify table here or the iterators will not work as you expect         }         //...         return strToReturn; } 

edit: facildelembrar pointed out (in the comments) that in modern C++ you can now rewrite the loop

for (auto& item: table) {     ... } 
like image 197
Tom Leys Avatar answered Sep 19 '22 04:09

Tom Leys