问题描述
如何在 C++ 中使用 3 维向量?
vector>>vec(1,vector<vector<int>>(1,vector<int>(1,12)));
当我尝试这样的事情时
cout <<vec[0][0][0];vec[0][0][1] = 13;
一切正常.
问题是我只能更改最后一个元素.如果我尝试访问第一个和第二个元素,就像这样
vec[0][1][0] = 13;
或者这个
vec.push_back(vector<vector<int > >());vec[0].push_back(vector());v[1][0].push_back(13);
我的程序崩溃了.
如何添加和访问 3d 矢量中的元素?
vector>>vec(1,vector<vector<int>>(1,vector<int>(1,12)));cout<<vec[0][0][0];vec[0][0][1] = 13;
一切正常.
你错了.一切都不好.向量 vec[0][0]
只有一个元素,因此 vec[0][0][1]
越界,因此赋值有未定义的行为.vec[0][1][0] = 13;
和 v[1][0].push_back(13)
您可以通过仅访问向量中存在的索引来解决该问题.如果你想要多个元素,那么要么一开始用更多元素构建向量,要么在构建后推送它们.
一开始我有 1x1x1 向量.那么我该如何推送元素.使用 push_back() 吗?例如我有 1x1x1 并且我想添加 v[1][1][0] = 2 ?
如果您出于某种原因想要从整数向量的向量的 1x1x1 向量开始并希望访问 v[1][1][0]
,这里是添加 v[1][1][0]
的示例代码code>v[1][1][0] 元素对原始向量的改动最小:
//包含一个元素 2 的整数向量//这将向量最终成为 v[1][1] 并且整数元素将成为 v[1][1][0]//由于我们将整数初始化为 2,因此无需稍后分配它向量六(1、2);//包含一个默认构造向量的向量向量//vvi 最终将是 v[1] 元素,默认构造向量将是 v[1][0]vectorvvi(1);//将 vi 推入 vvi,使其成为 vvi[1] 并最终成为 v[1][1]vvi.push_back(vi);//将 vvi 推入 v,使其成为 v[1]v.push_back(vvi);
How can I work with a 3 dimensional vector in C++?
vector<vector<vector<int> > > vec (1,vector<vector<int> >(1,vector <int>(1,12)));
When I try something like this
cout << vec[0][0][0]; vec[0][0][1] = 13;
everything works just fine.
The problem is that I can only change the last elements. If I try accessing the first and second element, like this
vec[0][1][0] = 13;
or this
vec.push_back(vector<vector<int > >());
vec[0].push_back(vector<int>());
v[1][0].push_back(13);
my program crashes.
How can I add and access elements in a 3d vector?
vector<vector<vector<int> > > vec (1,vector<vector<int> >(1,vector <int>(1,12)));
cout << vec[0][0][0]; vec[0][0][1] = 13;
You are mistaken. Everything is not OK. The vector vec[0][0]
has only one element and thus vec[0][0][1]
is out of bounds and therefore the assignment has undefined behaviour. You have the same problem with vec[0][1][0] = 13;
and v[1][0].push_back(13)
You can fix that by accessing only indices that exist in your vectors. If you want more than one element, then either construct the vectors with more elements initially, or push them after construction.
If you for some reason want to start with 1x1x1 vector of vectors of vectors of ints and want to access v[1][1][0]
, here is example code to add the v[1][1][0]
element with minimal changes to the original vector:
// vector of ints that contains one element, 2
// this will vector eventually be the v[1][1] and the integer element will be v[1][1][0]
// since we initialize the integer as 2, there's no need to assign it later though
vector<int> vi(1, 2);
// vector of vectors that contains one default constructed vector
// vvi will eventually be the v[1] element and the default constructed vector will be v[1][0]
vector<vector<int>> vvi(1);
// push vi into vvi, making it vvi[1] and eventually v[1][1]
vvi.push_back(vi);
// push vvi into v, making it v[1]
v.push_back(vvi);
这篇关于使用 3 维向量的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!