繁体   English   中英

为什么 std::vector 允许使用 [] 来分配,但 size() 和 capacity() 没有改变?

[英]why std::vector allow to use [] to assign, but the size() and capacity() doesn't change?

我进行如下测试,创建一个向量并将其容量设置为 1,然后使用v[100]=100; 直接赋值v[100]但是不触发core dump,为什么?向量v应该没有足够的内存来访问v[100],但是v[100]却成功被赋值为100,大小和容量( ) 仍为 0 和 1,如何理解?

int main(){
    std::vector<int> v;
    v.reserve(1); 
    v[100]=100;                      //here does't triggle core dump, wired
    std::cout<<v.size()<<std::endl;  //0 
    std::cout<<v.capacity()<<std::endl; //1
    std::cout<<v[100]<<std::endl;    //100
return 0;
}

这是因为std::vector::operator[]不做边界检查。 如果您使用无效的索引,则会导致未定义的行为。

如果你想要边界检查,那么你应该使用std::vector::at 如果您使用无效索引,它将引发异常。

v.at(100)=100; // this will throw a std::out_of_range exception

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM