如何在不知道大小的情况下将向量输入到向量中?

How to take input in a vector inside a vector without knowing it's size?

所以我有一个问题要求我输入一个变量列表列表,我只得到了列表大小而不是其中变量列表的长度。

输入:

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

INPUT 的第一行是列表列表的大小,后面是每个列表的输入,这些列表的大小是可变的。如何在 C++ 中的 vector<vector<int>> 中获取此输入?

您可以使用std::getline()输入每一行,然后使用istringstreamstd::stoistrings解析为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;
}

您可以在 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