[英]Initializations of a vector
I saw different ways to initialize vectors from an array (c-style or std::array) in C++11. 我看到了从C ++ 11中的数组(C样式或std :: array)初始化向量的不同方法。 Suppose I have an array like this :
uint8_t arr[5000]
or like this : std::array<uint8_t, 5000> arr;
假设我有一个这样的数组:
uint8_t arr[5000]
或这样的std::array<uint8_t, 5000> arr;
: std::array<uint8_t, 5000> arr;
as an example. 举个例子。
If I want the 5000 values from arr, I can initialize it these ways : 如果我想从arr中获得5000个值,则可以通过以下方式对其进行初始化:
std::vector<uint8_t> vect(arr, arr + 5000);
std::vector<uint8_t> vect(std::begin(arr), std::end(arr));
std::vector<uint8_t> vect(arr.begin(), arr.end());
This one apply if arr is an std::array<uint8_t, 5000>
) 如果arr是
std::array<uint8_t, 5000>
),则适用此方法
According to this answer , option 3 is better than option 1 and 2. It's better to use member function of the container instead of non-member functions. 根据此答案 ,选项3优于选项1和2。最好使用容器的成员函数而不是非成员函数。
I always saw the first option for c-style arrays. 我总是看到c样式数组的第一个选择。 Is the option 1 is exactly the same as the option 2 ?
选项1是否与选项2完全相同? What's the subtleties behind that ?
其背后的微妙之处是什么?
Thanks for your help. 谢谢你的帮助。
The preferred way is to put the values directly into the vector to start with, rather than putting them into an array, then using it to initialize the vector. 首选方法是将值直接放入向量中,而不是将它们放入数组中,然后使用它来初始化向量。
Barring that, the version using the free functions std::begin
and std::end
is generally preferable over the alternatives. 除此以外,使用自由函数
std::begin
和std::end
的版本通常比其他版本更可取。 It works whether the source is an array, std::vector
, std::array
, or one of the other containers such as std::list
, or std::set
. 无论源是数组,
std::vector
, std::array
还是其他容器之一,例如std::list
或std::set
。
The latter is obviously of greatest important in generic code, so it can be independent of the type of the source container. 后者显然在通用代码中最重要,因此它可以独立于源容器的类型。 Even otherwise, however, being able to use identical syntax for essentially all types of input makes it one more thing you can recognize as a high-level pattern, so you don't need to spend brain-cycles on figuring out what it's doing.
但是,即使在其他情况下,对于几乎所有类型的输入都可以使用相同的语法,这使您可以将其识别为高级模式,这是一件事,因此您无需花费脑力来弄清楚它在做什么。
There are two obvious disadvantages: 有两个明显的缺点:
begin
and end
as free functions. begin
和end
作为自由函数实现。 In my opinion, the best cure for this is to implement them yourself if needed (minimal effort). container.begin()
and container.end()
. container.begin()
和container.end()
。 Modifying a large existing code base to use the free functions may not be practical, and having a mixture of x.begin()
and begin(x)
won't help readability. x.begin()
和begin(x)
将无法提高可读性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.