在 c++ 中赋值给二维向量

Assigning to a two dimensional vector in c++

本文关键字:二维 向量 c++ 赋值      更新时间:2023-10-16
#include<bits/stdc++.h>
using namespace std;
main()
{
vector<vector<int> > v;
for(int i = 0;i < 3;i++)
{
vector<int> temp;
for(int j = 0;j < 3;j++)
{
temp.push_back(j);
}
//cout<<typeid(temp).name()<<endl;
v[i].push_back(temp);
}
}

我正在尝试分配给二维向量。我收到以下错误

No matching function for call to 
std ::vector<int>::push_back(std::vector<int> &)

问题:您的向量v还为空,如果不在 v 中推送任何向量,您将无法访问v[i]

解决方案:将语句v[i].push_back(temp);替换为v.push_back(temp);

您可以按照以下过程进行操作:

#include<bits/stdc++.h>
using namespace std;
int main()
{
vector<vector<int> > v;
for(int i = 0;i < 3;i++)
{
vector<int> temp;
for(int j = 0;j < 3;j++)
{
temp.push_back(j);
}
//cout<<typeid(temp).name()<<endl;
v.push_back(temp);
}
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
cout << v[i][j] << " ";
}
cout << endl;
}
}

v[0]为空,则应使用v.push_back(temp);

您可以使用at方法来避免此错误:

for(int i = 0; i < 3; i++){
vector <vector <int> > v;
vector <int> temp;
v.push_back(temp);
v.at(COLUMN).push_back(i);
}

然后,您可以通过以下方式访问它:

v.at(COLUMN).at(ROWS) = value;
v[i].push_back(temp);

应该是

v.push_back(temp);

vstd::vector<vector<int>>的类型,v[i]std::vector<int>的类型

你应该使用v而不是v[i]。(C++11(

#include <iostream>
#include <vector>
using namespace std;
int main(int argc, char* argv[])
{
vector<vector<int> > v;
for(int i = 0;i < 3;i++)
{
vector<int> temp;
for(int j = 0;j < 3;j++)
{
temp.push_back(j);
}
v.push_back(temp);
}
for (auto element: v) {
for (auto atom: element) {
cout << atom << " ";
}
cout << "n";
}
return 0;
}

可以这样想:"如何将T类型的可变温度插入我的std::vector<T>向量中?在您的情况下,它是:

v.push_back(temp);

T本身是一个向量并没有区别。然后要打印出(向量(的向量,您可以使用两个for循环:

for (std::size_t i = 0; i < v.size(); i++){
for (std::size_t j = 0; j < v[i].size(); j++){
std::cout << v[i][j] << ' ';
}
std::cout << std::endl;
}

就这么办吧...

#include<bits/stdc++.h>
using namespace std;
int main()
{
vector<vector<int> > v;
for(int i = 0; i < 3; i++)
{
vector<int> temp;
for(int j = 0; j < 3; j++)
{
temp.push_back(j);
}
v.push_back(temp);//use v instead of v[i];
}
}