Jasmine
Jasmine

Reputation: 16185

using istringstream to tokenize std::string to std::map

I have a vector that contains data like:

std::vector<std::string> v;

v[0] = "first:tom";
v[1] = "last:jones";

and I want to iterate through the vector and parse at : and put results in a std::map

std::vector<std::string> v;
std::map<std::string, std::string> m;
std::pair<std::string, std::string> p;

for(int i = 0; i < v.size(); i++) 
{
    std::cout << v[i] << std::endl;

    std::istringstream oss(v[i]);
    std::string token;

    while(getline(oss, token, ':')) 
    {
        m.insert(std::pair<std::string, std::string>("", ""));
    }               
 }

I am stuck on insertion to the std::map because I dont see how the parse gives me both pieces that I can insert into the map.

It isn't v[i] in both.

I want:

m.insert(std::pair<std::string, std::string>("first", "tom"));
m.insert(std::pair<std::string, std::string>("last", "jones"));   

Can anyone explain my difficulty?

Upvotes: 1

Views: 1211

Answers (4)

Mike Kinghan
Mike Kinghan

Reputation: 61462

And yet another option (C++11):

std::vector<std::string> v = { "first:tom", "last:jones" };
std::map<std::string,std::string> m;

for (std::string const & s : v) {
    auto i = s.find(':');
    m[s.substr(0,i)] = s.substr(i + 1);
}

Upvotes: 0

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24133

Use std::transform:

transform(v.begin(), v.end(), inserter(m, m.begin()), chopKeyValue);

Where chopKeyValue is:

pair<string, string> chopKeyValue(const string& keyValue) {
    string::size_type colon = keyValue.find(':');
    return make_pair(keyValue.substr(0, colon), keyValue.substr(colon+1));
}

Upvotes: 1

Sceptical Jule
Sceptical Jule

Reputation: 917

Try

std::vector<std::string> v;
std::map<std::string, std::string> m;

for(int i = 0; i < v.size(); i++) 
{
    std::cout << v[i] << std::endl;

    size_t sepPosition = v[i].find (':');
    //error handling
    std::string tokenA = v[i].substr(0, sepPosition);
    std::string tokenB = v[i].substr(sepPosition + 1)

    m.insert(std::pair<std::string, std::string>(std::move(tokenA), std::move(tokenB)));            
 }

Upvotes: 3

Dark Falcon
Dark Falcon

Reputation: 44191

Something like this:

std::vector<std::string> v;
std::map<std::string, std::string> m;
std::pair<std::string, std::string> p;

for(int i = 0; i < v.size(); i++) 
{
    std::cout << v[i] << std::endl;

    std::istringstream oss(v[i]);
    std::string key;
    std::string value;

    while(getline(oss, key, ':') && getline(oss, value)) 
    {
        m.insert(std::pair<std::string, std::string>(key, value));
    }               
 }

Upvotes: 2

Related Questions