在 std::vector c++ 中存储许多元素

Storing many elements in std::vector c++

本文关键字:存储 许多 元素 c++ std vector      更新时间:2023-10-16

对于我的一个应用程序,我需要生成大小为 2^35 的向量(我的 RAM 大小为 96 GB,因此该向量可以轻松放入 RAM)。

int main ()
{
  int i;
  /* initialize random seed: */
  srand (time(NULL));
  vector<int> vec;
  do {
     i = rand() % 10 + 1;
     vec.push_back(i);
  } while ((vec.size()*sizeof(int))<pow(2,35));
  return 0;
}

但是,我注意到我的 do while 循环无限执行。可能的原因之一是vec.size()的范围是长无符号int,它非常小于插入的元素数量,即 pow(2,35) ,因此我认为它进入了一个无限循环。我可能错了。如果我错了,请纠正我。但是有人可以告诉我如何在 vec 中插入超过 pow(2,35) 个数字。

GCC 版本:4.8.2

我将尝试通过一个简单的解决方案来解决您的一些问题:

你遇到的第一个问题是空间。由于您只需要 1-10 之间的数字,因此int8_t会更好地为您服务。

其次是速度。 std::vector幕后做了很多分配和重新分配。由于您有固定的大小,因此我认为没有必要使用它。知道了这一点,我们将使用一个简单的数组和线程来提高性能。

代码如下:

#include <array>
#include <random>
#include <thread>
#include <cstdint>
#include <memory>
#include <chrono>
// Since you only need numbers from 1-10, a single byte will work nicely.
const uint64_t size = UINT64_C(0x800000000); // Exactly 2^35
typedef std::array<int8_t, size> vec_t;
// start is first element, end is one-past the last. This is a template so we can generate multiple functions.
template<unsigned s>
void fill(vec_t::iterator start, vec_t::iterator end) {
    static const int seed = std::chrono::system_clock::now().time_since_epoch().count()*(s+1);
    static std::default_random_engine generator(seed);
    static std::uniform_int_distribution<int8_t> distribution(1,10);
    for(auto it = start; it != end; ++it) {
        *it = distribution(generator);  // generates number in the range 1..10
    }
}
int main() {
    auto vec = std::unique_ptr<vec_t>(new vec_t());
    // Each will have its own generator and distribution.
    std::thread a(fill<0>, vec->begin(), vec->begin() + size/4);
    std::thread b(fill<1>, vec->begin() + size/4, vec->begin() + size/2);
    std::thread c(fill<2>, vec->begin() + size/2, vec->begin() + (size/4)*3);
    std::thread d(fill<3>, vec->begin() + (size/4)*3, vec->end());
    a.join();
    b.join();
    c.join();
    d.join();
    return 0;
}

为什么不能使用构造函数?

std::vector<int> vec ( number_of_elements );

这样你就保留了内存,然后你可以使用 generate 或其他东西随机化元素。

更新

正如 Baum mit Augen 所强调的那样,这篇文章并没有真正回答这个问题,因为在他的平台中,条件 4 不成立(sizeof(std::size_t)实际上是8)。但是,我将这篇文章留在这里以强调移植代码时可能发生的问题。

原始帖子

我看到的一个问题如下。让我们假设(大多数平台都满足这些假设)

1)vec.size退货std::size_t(不保证);

2)sizeof退货std::size_t(保证);

3)std::size_t是无符号整数类型(保证);

4) sizeof(std::size_t) == 4(不保证);

5)CHAR_BIT == 8(不保证)。

(回想一下,CHAR_BITchar中的位数。

因此,vec.size()*sizeof(int)的类型std::size_t,其最大值为 2^(sizeof(std::size_t)*CHAR_BIT) - 1 == 2^32 - 1 < 2^32 < 2^35 。因此,vec.size()*sizeof(int)总是小于 2^35