在对循环缓冲区进行基准测试时,我偶然发现了这一点.任何人都可以解释一下std :: vector如何在这个实例中胜过普通数组?
#include <iostream>
#include <vector>
struct uint_pair {
unsigned int a, b;
uint_pair (unsigned int x = 0, unsigned int y = 0) : a(x), b(y) {}
};
struct container {
unsigned int pos;
#ifdef USE_VECTOR
std::vector<uint_pair> data;
container() : pos(0) { data.resize(16); }
#else
uint_pair data[16];
container() : pos(0) {}
#endif
void add(uint_pair val) {
data[++pos % 16] = val;
}
};
int main() {
container c;
for (unsigned int i = 0; i < 1000000000; i++) …Run Code Online (Sandbox Code Playgroud)