在 C++ 向量中访问超出大小的元素 [英] Access the element out of size in C++ vector

查看:26
本文介绍了在 C++ 向量中访问超出大小的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我在 VS2012 和 Max OS 10.7 中尝试了这样的事情

Today I try something like this in VS2012 and Max OS 10.7

    vector<int> vec;
    vector<int> vec2;
    for(int i = 0;i < 100 ;i++){
        vec.push_back(i);
    }

    cout << "size: " << vec.size() << endl;
    cout << "capacity: " << vec.capacity() << endl;
    cout << vec[127] << endl;
    //vec2.reserve(10);
    fill_n(vec.begin(),128,-1);
    cout << vec[127] << endl;
    return 0;

我们知道vector的大小是容器中元素的实际数量,上面的代码在VS2012中会导致运行时错误,但在Max OS上运行良好,我在Ideone.com 并且运行成功,我不确定大小和容量的定义是否有问题,为什么我可以访问超出大小的元素?

as we know the size of vector is the real number of elements in the container, the code above can cause runtime error in VS2012, but it works fine on Max OS, and I try it in Ideone.com and also run successfully, I am not sure if something wrong with the definition of size and capacity, why I can access element out of size?

PS:这种情况下我电脑的容量在 VS2012 上是 141,在 Mac OS 和 Ideone.com 上是 128

PS: the capacity at this situation on my computer is 141 on VS2012 and 128 on Mac OS and Ideone.com

推荐答案

std::vector operator [] 不会抛出任何超出范围的错误.使用 [] 运算符访问大于向量大小的元素是一种未定义的行为.

std::vector operator [] won't throw any out of range error. It's a undefined behaviour to access element greater than the vector size using [] operator.

使用std::vector::at 相反,它抛出 std::out_of_range

这篇关于在 C++ 向量中访问超出大小的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆