Jump to content
  • Advertisement
Sign in to follow this  

A fast way of filling std::map

This topic is 4275 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have a file which has the following kind of structure: fooo 7214 bar 12 foofoo 1234 ... What would be a quick way of filling up a std::map<std::string, unsigned> container with these lines found from the file? I think my previous approaches have been a bit clumsy and I'm fairly confident that this could be achieved in a more convenient way. Any help is appreciated, thanks in advance! [Edited by - Marmis on January 2, 2007 10:29:05 AM]

Share this post

Link to post
Share on other sites
What's wrong with:

string key;
unsigned int val;
while (fileIn >> key) { fileIn >> val; themap[key] = val; }


Share this post

Link to post
Share on other sites
#include <iostream>
#include <sstream>
#include <string>
#include <map>

template<class Key, class Value, class Pred, class Alloc>
int load_map( std::istream& is, std::map<Key, Value, Pred, Alloc>& m )
std::string line;
std::istringstream iss;
std::pair<Key, Value> data;
int errors = 0;

// Remove leading whitespace
is >> std::ws;

// Get the rest of the line
getline(is, line);

// Treat # as marking the beginning of a comment.
int comment = line.find('#');
if (comment != std::string::npos)
line.erase( comment );

// Nothing to do if the line is empty.
if (line.empty())

// Read the map fields.
iss >> data.first >> data.second;

// If successful, put the data in the map.

return errors;

std::string test =
"abc 123\n" // Reads ok
" def 456\n" // Reads ok, leading whitespace is removed
"ghi\n" // Missing field, skipped
"\n" // Empty, skipped
"klm 789 # howdy ?\n" // Reads ok
"nop #999\n" // Field commented out, skipped
"#qrs 343\n" // Line commented out, skipped
"tuv wxy" // Second field is garbage, skipped

int main()
std::istringstream iss(test);
std::map<std::string, int> m;
int errors = load_map(iss, m);

std::map<std::string, int>::iterator itor;
for(itor = m.begin(); itor != m.end(); ++itor)
std::cout << itor->first << ' ' << itor->second << std::endl;

std::cout << errors << " read errors." << std::endl;

[Edited by - Fruny on November 6, 2006 1:52:56 PM]

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!