c++ - ostream_iterator 的模板参数 - 每个元素都是对

标签 c++ templates iterator std-pair

我正在尝试使用 ostream_iterator 将成对 vector 写入文件。ostream_iterator 需要在声明时应用模板参数。 vector 定义为-

vector<pair<string,long>> test;

当我将 pair 作为模板传递给 ostream_iterator 时,它显示错误 -

Error 1 error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'const std::pair<_Ty1,_Ty2>' (or there is no acceptable conversion) C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\iterator 531 1 wordsegmentation

在这种情况下,正确的论点是什么?

编辑- 代码片段

vector<pair<string,long>> t;
......
//t is filled up with elements 
ostream_iterator<pair<string,long>> output_iterator(out, "\n");
std::copy(t.begin(), t.end(), output_iterator);

最佳答案

没有operator <<对于 std::pair .您不能简单地使用 ostream_iteratorstd::pair .

您可以使用派生自 pair 的其他东西或编写类, 或者那家店pair并使用它。您不能在 std 中编写重载命名空间,因为它会导致未定义的行为,并且您不能在全局命名空间中重载此运算符,因为 ADL将找不到正确的重载(如果您使用 STL 算法,如 copyostream_iterator )。

简单地说,像这样的东西会很好用

#include <iostream>
#include <utility>
#include <algorithm>
#include <iterator>

int main()
{
   std::vector<std::pair<int, int>> vec =
   {
      {1,1},
      {2,2}
   };
   for (const auto& p : vec)
   {
      std::cout << p.first << " " << p.second << std::endl;
   }
}

关于c++ - ostream_iterator 的模板参数 - 每个元素都是对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16956390/

相关文章:

c++ - 使用其指针从列表中删除项目

C++:使用 "strtol"检查字符串是否为有效整数

c++ - 对类型 'Item *const' 的引用无法绑定(bind)到类型 'const Item *' 的右值

C++模板特化问题

c++ - 我可以在这里使用 Curiously Recurring Template Pattern (C++) 吗?

c++ - 未取消引用的迭代器是否超过了数组未定义行为的 "one past-the-end"迭代器?

collections - 如何通过获取可变变量的所有权来替换它的值?

c++ - 如何从 C++ 中的双变量正态分布和学生 T 分布生成随机样本?

c++ - Qt 程序与另一个编译器崩溃

c++ - 错误 : expected primary-expression before ‘>’ : templated function that try to uses a template method of the class for which is templated