【发布时间】: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;
}
}
'''
【问题讨论】: