简体   繁体   中英

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?

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM