0

有没有办法通过生成器(类似于)构造函数参数来构造一个std::vector具有未初始化(非零)值甚至更漂亮的新值,该构造器参数在首先将所有元素初始化为零的情况下产生所需的非标准(非常量)值?这是因为我希望(随机)模型创建 api 尽可能地高效,从而只编写一次容器元素。为(可能还有其他人)拥有一个生成器构造器不是很好吗?!为什么 C++ 还没有将它添加到标准中?std::generate_n()std::vector

以下类似构造函数的 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().

4

1 回答 1

3

您可以在使用生成器之前调用vector::reserve. 这将具有与您显示的 C 代码完全相同的行为。您仍然需要使用 a 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;
}
于 2012-01-30T00:15:14.750 回答