直接使用operator []设置std :: vector内容 [英] Setting std::vector contents directly using operator []

查看:137
本文介绍了直接使用operator []设置std :: vector内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到,如果我用 std :: vector< int> 做了 vec [0] = 1 c>, vec.size()仍保留 0



然而,我仍然可以 vec [0] 检索我的 1



这是在未定义行为的范围吗?这里发生了什么?这是简单地写入 1 到保留的内存空间,我应该期望这爆炸在我的脸,对吗?



[]

code> 不检查范围,也不添加元素。你正在做的是写入和读取向量使用的缓冲区,但这被认为是未定义的行为。






您应该使用这些方法之一添加到向量。



.push_back 默认方法 - 附加到结尾



.resize(num,0)向量向上(或向下)调整为 num ,并将新元素的值设置为第2个arg,0 。



向量也可以用初始大小构建 - 0)几乎等同于 v = vector(); v.resize(num,0)






另一方面,为了安全起见,您可以使用 .at(n)访问元素,如果您访问超出范围,这将抛出 std :: out_of_range 例外边界。


I notice that if I do vec[0] = 1 with a fresh empty std::vector<int>, vec.size() remains 0.

However I can then still do vec[0] to retrieve my 1.

Is this in the realm of undefined behavior? What is going on here? Is this simply writing the 1 into reserved memory space, and I should expect this to blow up in my face, right?

解决方案

It is indeed Undefined behavior

[] Does not check bounds and does not add elements. What you are doing is writing to and reading from the buffer which vector uses, but that is considered undefined behavior.


You should use one of these methods to add to vectors.

.push_back(0) the default method - appends to the end

.resize(num,0) resizes the vector up (or down) to num and sets the value of the new elements to the 2nd arg, 0.

The vector can also be constructed with an initial size - vector(num,0) is more or less identical to v = vector();v.resize(num,0)


On the other end, to do this safely, you can use .at(n) to access elements, and this will throw an std::out_of_range exception if you access beyond the bounds.

这篇关于直接使用operator []设置std :: vector内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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