有没有办法用未初始化(非零)值或什至通过生成器构建一个新的std::vector
(类似于 std::generate_n()
)生成所需非标准(非常量)值的构造函数参数无需首先将所有元素初始化为零?这是因为我希望(随机)模型创建 api 尽可能地高效,从而只编写一次容器元素。为 std::vector
(以及可能的其他)提供一个生成构造函数不是很好吗?!为什么 C++ 还没有将它添加到标准中?
下面类似构造函数的 C 函数说明了我为 std::vector
的自定义初始化构造寻求的一次写入行为:
// Allocate-and-Generate a random int array of length \p n.
int * gen_rand(size_t n)
{
int *v = malloc(n); // allocate only
for (size_t i=0; i<n; i++) {
v[i] = rand(); // first write
}
}
我认为这归结为所使用的 STL 分配器的行为,因为它负责写入(或不写入)初始零。
如果我们将 std::vector
构造函数与迭代器一起使用,我们首先必须在其他地方分配和写入随机值,这比使用 push_back()
更糟糕。
最佳答案
您可以在使用生成器之前调用 vector::reserve
。这将具有与您显示的 C 代码完全相同的行为。您仍然需要使用 back_insert_iterator
,因为 vector
的大小仍为零。
#include <vector>
#include <cstdlib>
#include <algorithm>
#include <iterator>
#include <iostream>
int main()
{
std::vector<int> v;
v.reserve(10);
std::generate_n(std::back_inserter(v), 10, []() { return rand(); });
for(auto x : v)
std::cout << x << std::endl;
// unsafe version
std::vector<int> v2;
// 10 uninitialized integers
v2.resize(10);
// make sure never to write more than the exact amount, otherwise this will be UB
std::generate_n(v.begin(), 10, []() { return rand(); });
return 0;
}
关于c++ - 构造期间的非常量生成器单遍初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9054176/