2

My input : the first input is number of lines the input will contain

5
7 3 29 0
3 4 3 
2 3 4 55 5
2 3
1 2 33 4 5

My issue is how can I store them in vector of vector..?

My concept..

.
.
.
cin>>n;
vector<vector<int>>vec;
while(n--)
{
    vector<int>vec2;
    for(**Getting input until the line**){
    vec2.emplace_back(input);}
    vec.emplace_back(vec2)
}

I need to implement that getting input till the line. For this I thought of getting the input as string and storing the values in vector vec2 using strtok after converting it to c_string... But I need to know whether there is any efficient way I can overcome this problem..

Zeros
  • 83
  • 4
  • 1
    Your idea is actually pretty accurate, as you don't exactly know how many numbers are in a line. For a beginner it would be far easier to do what you wanted and get the whole string - and then iterate over it. The general answer to iterating over a string by delimiters can be found [Here](https://stackoverflow.com/questions/236129/how-do-i-iterate-over-the-words-of-a-string) – Eugene Anisiutkin Oct 25 '21 at 16:31

1 Answers1

3

Here's my suggestion, YMMV.

  1. Read each line into a string.
  2. Use istringstream to extract the integers from the string, into a vector.
  3. After string is processed, push_back the vector into the outer vector.
    unsigned int rows;  
    std::cin >> rows;  
    std::string text_row;  
    for (unsigned int i = 0U; i < rows; ++i)  
    {  
        std::getline(cin, text_row);  
        std::istringstream numbers_stream(text_row);  
        std::vector<int>  row_data;  
        int number;  
        while (numbers_stream >> number)  
        {  
            row_data.push_back(number);  
        }  
        vec.push_back(row_data);  
    }  
Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
  • Use ```emplace_back()``` good practice ! – Zeros Oct 25 '21 at 18:29
  • If ```emplace_back``` have advantage over ```push_back``` then why ```push_back``` is still in the game? Does ```push_back``` have any unique feature..? – Zeros Oct 25 '21 at 18:31
  • Small nitpick - I would move `getline()` into the `for` loop condition, in case it fails: `for (unsigned int i = 0U; i < rows && std::getline(cin, text_row); ++i)` I would also change the outer `push_back()` to use `std::move()` to avoid an unnecessary copy: `vec.push_back(std::move(row_data));` Or, like Zeros implied, use `emplace_back()` instead: `auto &row_data = vec.emplace_back(); while (numbers_stream >> number) { row_data.push_back(number); }` – Remy Lebeau Oct 25 '21 at 19:19