1

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?

4 Answers 4

3

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)));            
 }
Sign up to request clarification or add additional context in comments.

2 Comments

This works and I like it make is clear by the 2 substroperations
@Jason: Be sure to check the value of sepPosition and confirm that is is not equal to std::string::npos.
2

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));
    }               
 }

Comments

1

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));
}

Comments

0

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);
}

1 Comment

Be sure to check the value of sepPosition and confirm that is is not equal to std::string::npos in real code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.