#include <iostream>
#include <vector>
int main()
{
std::vector<double> test1(1);
test1[100] = 5.;
std::vector< std::vector <double > > test2(1, std::vector<double>(1,0));
test2[50][100] = 5.;
}
test1: 很好地调整大小和分配内存
test2: "Segmentation fault (core dumped)". 为什么?
注意:不能使用矩阵,因为行大小不相等。
摘要:
at(int): 检查边界并在必要时抛出异常 - 无需调整大小
operator[](int):不检查边界 - 不调整大小
push_back():capacity()如果当前容量很小,调整大小会增加一倍
size(): 元素个数vector
capacity(): 在重新分配之前要持有的最大元素是必要的