以下代码始终有效还是依赖于编译器/平台?显然,我可以使用值构造函数初始化 edges
,但我很好奇当初始化 edges
时,复制赋值 operator=
是否可以在此处工作大小为 0,然后设置为等于大括号 r 值。
它适用于我的 MacBook。
std::vector<std::vector<int>> edges;
edges = {{1,2,3},{4},{5,6}};
最佳答案
它是有效的(自 C++11 起)。 std::vector
有一个重载的 operator=
采用 std::initializer_list
。
Replaces the contents with those identified by initializer list
ilist
.
和std::initializer_list
可以在指定的上下文中从花括号列表构造。
(强调我的)
A
std::initializer_list
object is automatically constructed when:
- a braced-init-list is used to list-initialize an object, where the corresponding constructor accepts an
std::initializer_list
parameter- a braced-init-list is used as the right operand of assignment or as a function call argument, and the corresponding assignment operator/function accepts an
std::initializer_list
parameter- a braced-init-list is bound to auto, including in a ranged for loop
关于c++ - 设置 vector 等于{};,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60123490/