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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With