C ++ - number of parses from std :: string

I need to iterate over the shopping list that I have nested in the vector and then separate each line by the quantity and item name. How can I get a pair with a number as the first element and the element name as the second?

Example:

vector<string> shopping_list = {"3 Apples", "5 Mandarin Oranges", "24 Eggs", "152 Chickens"}

      

I'm not sure how big the number will be, so I can't use a constant index.

Ideally I want a vector of pairs.

+3


source to share


3 answers


You can write a function to separate quantity and item as shown below:

#include <sstream>

auto split( const std::string &p ) {
    int num;
    std::string item;

    std::istringstream  ss ( p);
    ss >>num ; // assuming format is integer followed by space then item
    getline(ss, item); // remaining string
    return make_pair(num,item) ;
}

      

Then use std::transform

to get a vector of pairs:



std::transform( shopping_list.cbegin(),
                   shopping_list.cend(),
                   std::back_inserter(items), 
                   split );

      

See Here

+4


source


You can use std::stringstream

as follows.

vector< pair<int,string> > myList;
for(int i=0;i<shopping_list.size();i++) {
    int num;
    string item;
    std::stringstream ss;
    ss<<shopping_list[i];
    ss>>num;
    ss>>item;
    myList.push_back(make_pair(num,item));
    ...
}

      



num

is your required number.

+1


source


I offer you the following solution without stringstream

as an alternative solution

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main() {
    vector<string> shopping_list = { "3 Apples", "5 Mandarin Oranges", "24 Eggs", "152 Chickens" };
    vector< pair<int, string> > pairs_list;

    for (string s : shopping_list)
    {
        int num;
        string name;
        int space_pos = s.find_first_of(" ");
        if (space_pos == std::string::npos)
            continue; // format is broken : no spaces

        try{
            name = s.substr(space_pos + 1);
            num = std::stoi(s.substr(0, space_pos));
        }
        catch (...)
        {
            continue; // format is broken : any problem
        }
        pairs_list.push_back(make_pair(num, name));
    }

    for (auto p : pairs_list)
    {
        cout << p.first << " : " << p.second << endl;
    }

    return 0;
}

      

0


source







All Articles