是否更高效地设置向量的大小前面? [英] Is it more efficient to set the size of a vector up front?
问题描述
如果你能够,是否更有效地设置一个向量的大小前面?
如果您使用 .push_back()$ c $,那么我打算push_back值。解决方案 c>存储值,不正确使用 .resize()$ c设置向量的大小 $ c>成员函数。相反,您可以使用 .reserve()
成员函数向前设置向量的 capacity 。
这里有三种正确的方法:
// 1)最初不做任何操作,使用.push_back
std :: vector< int> v;
v.push_back(1); v.push_back(2);
// 2)最初设置容量,使用.push_back
std :: vector< int> v;
v.reserve(2);
v.push_back(1); v.push_back(2);
// 3)设置大小,使用下标
std :: vector< int> v(2); //在构造中设置大小
v.resize(2); //或通过调用.resize()设置大小
v [0] = 1; v [1] = 2;是的,第二种方法通常比第一种方法更具有尺寸和时间效率。 >
第二种方法有时比第三种方法更节省时间。或不。你应该测量它,看看它是否重要。
If you are able to, is it more efficient to set the size of a vector up front? I intend to push_back values.
解决方案 If you are using .push_back()
to store values, it is incorrect to "set the size of the vector up front" using the .resize()
member function. Rather, you would set the capacity of the vector up front using the .reserve()
member function.
Here are three correct approaches:
// 1) Do nothing initially, use .push_back
std::vector<int> v;
v.push_back(1); v.push_back(2);
// 2) Set the capacity initially, use .push_back
std::vector<int> v;
v.reserve(2);
v.push_back(1); v.push_back(2);
// 3) Set the size initiallly, use subscripts
std::vector<int> v(2); // Set the size in construction
v.resize(2); // OR set the size by a call to .resize()
v[0] = 1; v[1] = 2;
Yes, the 2nd approach is usually more size- and time-efficient than the first.
The 2nd approach is sometimes more time-efficient than the 3rd. Or not. You should measure it to see if it even matters.
这篇关于是否更高效地设置向量的大小前面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!