我曾经以为动态数组会很快,起码比vector快,然后我在VS2017的编译器试了一下。大家都可以试试。vector肯定针对系统底层的API做优化了,友情提供源代码。
int main()
{
int n;
cin >> n;
int *d = new int[n];
for (auto i = 0; i < n; ++i)
d[i] = rand();
time_t star;
/* vector<int> a(n);
star = clock();
for (auto i = 0; i <n; ++i)
a[i] = d[i];
std::cout << clock() - star << endl;
int *b = new int[n];
star = clock();
for (auto i = 0; i < n; ++i)
b[i] = d[i];
std::cout << clock() - star << endl;
delete[] b;
vector<int> c;
star = clock();
for (auto i = 0; i < n; ++i)
c.push_back(d[i]);
std::cout << clock() - star << endl;
vector<int> f;
f.reserve(n);
star = clock();
for (auto i = 0; i < n; ++i)
f.push_back(d[i]);
std::cout << clock() - star << endl;
delete[] d; */
int **b = new int *[n];
for (auto i = 0; i < n; ++i)
b[i] = new int[n];
star = clock();
for (auto i = 0; i < n; ++i)
for (auto j = 0; j < n; ++j)
b[i][j] = d[i] * d[i] + 1;
std::cout << clock() - star << endl;
for (auto i = 0; i < n; ++i)
delete[] b[i];
delete[] b;
vector<vector<int>> a(n);
for (auto &t : a)
t.resize(n);
star = clock();
for (auto i = 0; i < n; ++i)
for (auto j = 0; j < n; ++j)
a[i][j] = d[i] * d[i] + 2;
std::cout << clock() - star << endl;
int **p = (int **)malloc(n * sizeof(int *));
for (auto i = 0; i < n; ++i)
p[i] = (int *)malloc(n * sizeof(int));
star = clock();
for (auto i = 0; i < n; ++i)
for (auto j = 0; j < n; ++j)
p[i][j] = d[i] * d[i] + 3;
std::cout << clock() - star << endl;
for (auto i = 0; i < n; ++i)
free(p[i]);
free(p);
}