Как ввести вектор внутри вектора, не зная его размера? - PullRequest
0 голосов
/ 11 июля 2020

Итак, у меня возник вопрос, который потребовал, чтобы я ввел список списков переменных, из которых мне дали только размер списка, а не длины списков переменных внутри него.

INPUT:

3
1 5 7 2
3 6 2 6 2 4
6 2 3 5 3 

Первая строка INPUT - это размер списка списков, за которым следует ввод каждого списка, который имеет переменный размер. Как я могу ввести этот ввод внутри vector<vector<int>> в C ++?

Ответы [ 2 ]

2 голосов
/ 11 июля 2020

Вы можете использовать std::getline() для ввода каждой строки, а затем использовать istringstream или std::stoi для синтаксического анализа strings в ints.

#include <iostream>
#include <sstream>
#include <vector>
#include <string>

using namespace std;

vector <vector<int>> DATA;

int main(){
    int N;
    cin >> N;

    string input;
    for(int i = 0; i < N; ++i){
        getline(cin, input);
    
        istringstream my_stream(input);
        vector <int> curr;

        int num;
        while(my_stream >> num){
             curr.push_back(num);
        }
    
        DATA.push_back(curr);

        cin.ignore();
    }

    return 0;
}
1 голос
/ 11 июля 2020

Вы можете сделать это с помощью std::stringstream, как показано:

#include <iostream>
#include <string>
#include <sstream>
#include <vector>

using namespace std;

int main(void) {
    vector<vector<int>> mainVector{};
    string tempInput = "";
    int number = 0;
    int lines = 0;

    cout << "Enter the number of lines: ";
    cin >> lines;

    for (int i = 0; i <= lines; i++) {
        // temporary vector
        vector<int> tempVector{};
        // getting the entire inputted line from the user
        getline(cin, tempInput);

        // parsing the string into the integer
        stringstream ss(tempInput);

        // pushing the integer
        while (ss >> number)
            tempVector.push_back(number);
        
        mainVector.push_back(tempVector);
    }

    // displaying them back to verify they're successfully stored
    for (int i = 0; i <= lines; i++) {
        for (size_t j = 0, len = mainVector[i].size(); j < len; j++)
            cout << mainVector[i][j] << ' ';

        cout << endl;
    }

    return 0;
}

Пример вывода:

Enter the number of lines: 3 
1 5 7 2
3 6 2 6 2 4
6 2 3 5 3 

1 5 7 2     // printing the stored vector
3 6 2 6 2 4
6 2 3 5 3
...