vector实现数组访问的条件
通过两段代码测试,我们得出原则就是数组下标[]访问,前提就是这样的元素是存在的,就可以使用这样的访问形式,vector容器是重载了数组的访问形式。这一点程序员务必要小心,因为些这样的程序是编译通过的,但是运行的时候内存就会报错!
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector<int> test;
for (int i = 0; i < 10; i++)
test.push_back(i);
cout << test[0]<<endl;
test[0] = 10;
cout << test[0] << endl;
while (true)
{
}
}
运行平台VS2013,结果如期若下:
或者采用另外一种形式:先直接定义了容器的大小了,如下代码:
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector<int> test(10);
for (int i = 0; i < 10; i++)
test[i] = i;
cout << test[0]<<endl;
test[0] = 10;
cout << test[0] << endl;
while (true)
{
}
}
运行结果是完全一样的:
总结
通过对vector的测试,总结出一点就是要想实现数组下标的访问,是什么时候都可以的事情,应为vector是自带重载该符号功能,但对于编程人员来说需要特别关注访问的元素内存是否存在?!