Sign in to follow this  

A fast way of filling std::map

This topic is 4056 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
#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;

while(!is.eof())
{
// 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())
continue;

// Read the map fields.
iss.clear();
iss.str(line);
iss >> data.first >> data.second;

// If successful, put the data in the map.
if(!iss.fail())
m.insert(data);
else
++errors;
}

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

This topic is 4056 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this