#include <iostream>
#include <vector>
int main()
{
static const unsigned TOTAL = 4;
std::vector<int> v[TOTAL];
v[2].push_back(37);
//std::cout << v.size(); error
std::cout << v[0].size();
std::cout << v[2].size();
return 0;
}
是否可以像上面的代码一样使用括号std::vector
安装?
MSVS和ideone编译得很好,但是向量混乱(参见错误行)。
我知道我可以使用resize
,但这里发生了什么?
答案 0 :(得分:5)
您正在创建一个TOTAL
大小的矢量数组。
您需要的是
std::vector<int> v(TOTAL);
这构造了一个TOTAL
零初始化ints
的矢量。
然后,
std::cout << v.size() << std::endl; // prints 4
std::cout << v[0] << std::endl; // prints 0
等等。
答案 1 :(得分:1)
在代码中使用括号实例化std::vector
是有效的,但具有不同的含义。
std::vector<int> v[TOTAL];
您在此处定义了v
的向量size=TOTAL
,其中每个元素都是vector<int>
。最初,这些TOTAL
vector<int>
都是空的(即size=0
)。
致电v[2].push_back(37);
后,v[2]
将成为vector<int>
size=1
,其中包含值37
。
因此,您对以下内容的输出将为0
和1
。
std::cout << v[0].size();
std::cout << v[2].size();
如果您想致电size()
,请拨打v[i].size()
或将其定义为vector<int> v(TOTAL);
(v
是size=TOTAL
的向量,每个元素都包含int
这是{{1}})。
答案 2 :(得分:1)
我知道我可以使用调整大小,但这里发生了什么?
您基本上创建了一个std::vector<int>
类型的数组,就像在这里一样:
int arr[TOTAL];
是否可以像上面的代码一样用括号实例化std :: vector?
你可以拥有一系列向量,但是从你的帖子来看,它不是你想要的。
如果你想给你的矢量一些初始大小,那么使用
std::vector<int> v(TOTAL);
这会将矢量的初始大小设置为TOTAL,并且值初始化所有元素(将它们设置为零)。
但你可能真的想:
std::vector<int> v;
v.reserve(TOTAL); // this is not necessary
// v.size() is zero here, push_back will add elements starting from index 0
因为在std::vector<int> v(TOTAL);
的情况下,你的push_back将从索引TOTAL开始添加。