【发布时间】:2021-04-08 21:15:57
【问题描述】:
请参阅以下最小可重现示例:
#include <iostream>
#include <vector>
#include <algorithm>
// Define inserter operator for std::vector<int>
std::ostream& operator << (std::ostream& os, const std::vector<int>& v) {
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(os, " "));
return os;
}
// Define inserter operator for std::vector<std::vector<int>>
std::ostream& operator << (std::ostream& os, const std::vector<std::vector<int>>& vv) {
// ******* Error in this line *****
std::copy(vv.begin(), vv.end(), std::ostream_iterator<std::vector<int>>(os,"\n"));
// OK. The following works and will call the operator above
for (const std::vector<int>& v : vv) os << v << '\n';
return os;
}
int main() {
std::vector<std::vector<int>> vvi{ {1,2}, {3,4,5}, {6,7,8,9 } };
std::cout << vvi;
return 0;
}
std::ostream_iterator<std::vector<int>> 不会编译,编译器说:
二进制 '
虽然std::vector<int> 的插入运算符可用。
如果我改为使用:
for (const std::vector<int>& v : vv) os << v << '\n';
std::vector<int> 的插入运算符将被调用。但不是std::ostream_iterator。
CppReference 对我没有帮助。
为什么不编译?
【问题讨论】:
标签: c++ vector iterator ostream