【问题标题】:How to take input in a vector inside a vector without knowing it's size?如何在不知道向量大小的情况下将输入输入向量内?
【发布时间】:2020-07-11 18:16:13
【问题描述】:

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

输入:

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

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

【问题讨论】:

    标签: c++ vector io


    【解决方案1】:

    您可以使用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;
    }
    

    【讨论】:

    • 我在笔记本电脑上运行代码,但在输入 N 后似乎只需要一行输入,即使我将 N 输入为 2
    • 添加cin.ignore()
    • 好像你忘了实现vector library。
    • 打印值时,第一个向量中的第一个值丢失了!?
    【解决方案2】:

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

    【讨论】:

    • @SomeshwarRoychowdhury 不知道它是否有效。看看它是如何工作的。
    • 是的!但我不明白为什么上述解决方案需要 cin.ignore() 并且在上述解决方案中打印值时,第一个向量中不存在第一个值!你能解释一下吗?
    猜你喜欢
    • 2018-03-24
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-24
    • 2019-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多