【发布时间】:2020-02-13 23:50:25
【问题描述】:
我的代码有以下综合示例:
#include <vector>
#include <array>
#include <cstdlib>
#define CAPACITY 10000
int main() {
std::vector<std::vector<int>> a;
std::vector<std::array<int, 2>> b;
a.resize(CAPACITY, std::vector<int> {0, 0})
b.resize(CAPACITY, std::array<int, 2> {0, 0})
for (;;) {
size_t new_rand_size = (std::rand() % CAPACITY);
a.resize(new_rand_size);
b.resize(new_rand_size);
for (size_t i = 0; i < new_rand_size; ++i) {
a[i][0] = std::rand();
a[i][1] = std::rand();
b[i][0] = std::rand();
b[i][1] = std::rand();
}
process(a); // respectively process(b)
}
}
很明显,数组版本更好,因为它需要更少的分配,因为数组的大小是固定的并且在内存中是连续的(对吗?)。它只是在容量范围内再次向上调整大小时重新初始化。
因为无论如何我都要覆盖,所以我想知道是否有办法跳过初始化(例如,通过覆盖分配器或类似方法)以进一步优化代码。
【问题讨论】:
-
你知道emplace_back()怎么用吗?
标签: c++ arrays optimization vector allocator