4

I need to iterate through a shopping list which I have put into a vector and further separate each line by the quantity and item name. How can I get a pair with the number as the first item and the item 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 would like a vector of pairs.

97amarnathk
  • 957
  • 2
  • 11
  • 30

3 Answers3

4

You can write a function to split quantity and item like following:

#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 vector of pairs :

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

See Here

P0W
  • 46,614
  • 9
  • 72
  • 119
1

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.

97amarnathk
  • 957
  • 2
  • 11
  • 30
1

I suggest you the following solution without stringstream just as 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;
}
VolAnd
  • 6,367
  • 3
  • 25
  • 43