【问题标题】:Is there multiple ways to cin vector elements?是否有多种方法可以 cin 向量元素?
【发布时间】:2020-07-24 00:11:37
【问题描述】:

我有一个程序可以在 1 个向量中添加多个向量。我看到了一种代替 .push_back 的方法来添加元素并使用了它,但我想知道为什么这行得通,因为我认为 vector[] 表示索引,那么为什么 cin >> vector[] 将元素添加到向量中 if square括号表示索引? 输入输出 1 2; 5 4; 9 1 - 1 2; 5 4; 9 1

'''
    #include <vector>
    #include <iostream>
    using namespace std;
    int main()
    {
    int q = 3; //total number of q2 in q1
    vector<vector<int>> q1; //vector for q2's
        for(int a = 0; a < q; a++)
            {
            vector<int> q2(2); //making each q2 vector the size of 2 elements
            for(int b = 0; b < 2; b++){
                cin >> q2[b]; //adding elements to q2**how does this work instead of push_back?
                }
            q1.push_back(q2); //adding last q2 into q1
            }
    //printing q1
        for(int a = 0; a < q1.size(); a++){
            for(int b = 0; b < q1[a].size(); b++){
                cout << q1[a][b] << " ";
                }
            cout << endl;
            }
    }
'''

【问题讨论】:

    标签: c++ vector


    【解决方案1】:

    vector&lt;int&gt; q2(2) 生成一个向量 q2,其中包含 2 个默认构造的 int 元素。您不需要 push_back() 元素,因为它在构建时会为您生成 2 个元素。

    cin &gt;&gt; q2[b] 仅编辑向量中已存在的int 元素。

    【讨论】:

    • 所以当我创建 q2(2) 时,q2 中有两个可用空间,然后 cin >> q2[b] 允许我在循环完成后编辑这两个编辑,对吗?
    • 我想我认为 q2[b] 和 q2[cin'ing varaiable] 一样,但更重要的是 q2[b] 是像 cin >> x 这样的整个变量,而且碰巧这个'x' 表示 q2 处的索引,允许我编辑该索引处的元素。
    • @2Kbummer 它不只是让两个空间可用,它实际上默认构造了向量包含在这些空间中的两个对象。
    • @2Kbummer: cin &gt;&gt; q2[b];cin 读取到int 向量q2 已经在索引b 处创建。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多