可以使用”[]”而不是”push_back()”来初始化向量吗?

huangapple go评论68阅读模式
英文:

Whether can we initializing vectors using [] rather than push_back()

问题

使用[] 初始化向量时,我无法进行初始化。

std::vector<int> vectorVar;
vectorVar[0] = 0;

会导致未定义的行为。

而如果已经创建了向量,则可以使用以下方式:

vectorVar.push_back(0);
vectorVar[0] = 5;

但在映射的情况下,即使没有条目,也可以使用:

std::map<int, std::vector<int>> mapVar;
mapVar[0] = vectorVar;

请澄清。

谢谢与问候,
Vishnu Beema

如果"vectorVar[0] = 0;" 会导致未定义的行为。

英文:

As part of vectors, using [] I am not able to initialize.

std::vector&lt;int&gt; vectorVar;
vectorVar[0] = 0;

Seeing undefeined behaviour.

Whereas able to use only if its already created.

vectorVar.push_back(0);
vectorVar[0] = 5;

But in case of map able to use even if there is no entry.

std::map&lt;int, std::vector&lt;int&gt;&gt; mapVar;
mapVar[0] = vectorVar;

Please clarify.

Thanks & Regards
Vishnu Beema

Getting undefined behavior if "vectorVar[0] = 0;"

答案1

得分: 7

std::map::operator[] 与其他 [] 有些不同,因为它不仅仅是元素访问,它更多。

来自 cppreference

返回映射到等于键 key 的值的引用,如果不存在此类键,则进行插入。

当映射中没有具有给定键的元素时,将插入一个元素到映射中。

向量不工作方式相同。 std::vector::operator[] 不会向向量中插入元素。

总之,您需要获取一个引用,以便查找事物。 C++ 太复杂了,不可能记住一切。我建议参考 https://en.cppreference.com/,因为它通常与标准文件中的措辞相当接近,同时也非常可读。

英文:

std::map::operator[] is somewhat different from other [] because its not just element access. It is more.

From cppreference:

>Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist.

When no element is in the map with the given key then one is inserted into the map.

Vectors do not work like this. std::vector::operator[] does not insert elements into the vector.

In general you need to get a reference where you can look things up. C++ is too complicated to remember everything. I suggest https://en.cppreference.com/ because its usually rather close to the wording in the standard but at the same time very readable.

答案2

得分: 0

std::vector<T>是一个存储元素连续的容器。

std::vector<int> v;
v[5] = 1;

上面的代码将要求在v[0]v[4]之间插入0或其他值,这显然不是期望的行为,因此被禁止。

std::map<T>是一个稀疏容器,

std::map<int> m;
m[5] = 1;

上面的代码只向映射中插入一个单一元素。

英文:

std::vector&lt;T&gt; is a container of elements stored contiguously.

std::vector&lt;int&gt; v;
v[5] = 1;

The code above would require inserting 0 or whatever into v[0] till v[4]. This is definitely not what is expected thus forbidden.

std::map&lt;T&gt; is a sparse container,

std::map&lt;int&gt; m;
m[5] = 1;

The code above inserts just a single element into a map.

huangapple
  • 本文由 发表于 2023年3月15日 17:36:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75742862.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定