在 c++ 中赋值给二维向量
Assigning to a two dimensional vector in c++
#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);
v
是std::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];
}
}
相关文章:
- 我在二维向量中是否正确分配了内存
- 在二维向量或数组中可以存储的最大元素数是多少?
- 如何将整数字符串转换为整数的二维向量?
- 如何使用擦除和迭代器来删除二维向量中的项目
- 如何在二维向量c++中迭代col
- 如何在C++中将.csv文件的元素存储到二维向量中?
- std::vector::clear()ing 二维向量线程的内部向量安全吗?
- 在我为我的二维向量提供第一个值后控制台关闭
- 以C++输出二维向量
- 在 c++ 中赋值给二维向量
- 在二维向量的每一列中查找最大值
- 类对象初始化的二维向量
- 有没有办法像python:np.concatenate([x,y,z],axis=1)中那样沿着列连接三个二维向量C++
- 我如何在二维向量中存储一些数组
- 我可以push_back矩形形状到继承矩形形状的类的二维向量中吗?
- 二维向量的迭代器
- 在 STL 中,如何交换二维向量
- 创建一个二维向量阵列,遍历
- 创建二维向量的错误
- C++从文件中读取信息并从该信息构建二维向量