在 std::vector c++ 中存储许多元素
Storing many elements in std::vector c++
对于我的一个应用程序,我需要生成大小为 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_BIT
是char
中的位数。
因此,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
。
- 将字符串存储在c++中的稳定内存中
- std::原子加载和存储都需要吗
- C++:将控制台输出存储在宏中更好吗
- 使用QProcess执行命令,并将结果存储在QStringList中
- 访问存储在向量C++中的结构的多态成员
- 在混合代码库中将C转换为C++时出现许多包含错误
- 如何从存储在std::映射中的std::集中删除元素
- 存储模板类型以强制转换回派生<T>
- 类型总是使用其大小存储在内存中吗
- 当字符串存储在变量中时,如何将字符串转换为wchar_t
- 使用无符号字符数组有效存储内存
- 如何在cpp.中使用协议缓冲区存储大缓冲区/数组(char/int)
- 使用 pqxx 将 std::vector 存储在 postgresql 中,并从数据库中检索它
- 带结构的二维矢量:如何存储元素
- 添加存储在向量中的大整数的函数出现问题
- 我如何在2D数组中存储许多精灵
- 在共享内存中存储许多变量
- 在 std::vector c++ 中存储许多元素
- 传递许多函数并将其所有结果存储在元组中
- 为什么许多nosql存储都是用java编写的