c++ - 如何 vector<int> += 1,1,2,2,2,3,4,5,6;可能的?

标签 c++

我在 boost documentation 中发现了这个奇怪的语法.

std::vector<int> input;
input += 1,1,2,2,2,3,4,5,6; // <--- How is this possible?

最佳答案

这只是 Boost.Assignment图书馆。它使用 operator+=operator,重载使容器的分配更容易。

语法分解可以由 operator precedence 给出表。

本质上 input += 1将返回一个具有 operator, 的代理对象重载将执行顺序插入,大致相当于:

auto x = (input += 1); // input.push_back(1);
x,2; // input.push_back(2);
x,3; // input.push_back(3);

这是在 C++98 中还没有 std::initializer_list 的时候直接分配容器的内容,例如std::vector<int> x = { 1, 2, 3 }; .

关于c++ - 如何 vector<int> += 1,1,2,2,2,3,4,5,6;可能的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26207646/

相关文章:

c++ - ncurses 中的关键常量错误

javascript - 未调用 Bracket-Shell 自定义 native (C++) 函数

c++ - int (*p) 和 int *p 有区别吗?

c++ - 当类的对象正在更改其参数时如何获取结果

c++ 从文本文件中删除行(需要解释)

c++ - 为什么我们可以取消引用函数指针?

c++ - 无法捕获 c++ 中的异常 : failure to identify exception type

c++ - Ogre SDK 出现异常

c++ - 强制转换和 namespace 运算符之间没有空格?

c++ - 将二进制文件读取到 "unsigned char" vector 时的模板参数是什么