Vector用数组下标访问的条件

来源:互联网 发布:三防漆涂覆机编程 编辑:程序博客网 时间:2024/05/20 22:01

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是自带重载该符号功能,但对于编程人员来说需要特别关注访问的元素内存是否存在?!

阅读全文
0 0
原创粉丝点击