c++ - 为什么这个 C++ STL 代码编译失败

标签 c++

Compilation error

/usr/include/c++/7/bits/stream_iterator.h:199:13: error: no match for ‘operator<<’ (operand types are ‘std::ostream_iterator > >::ostream_type {aka std::basic_ostream}’ and ‘const std::pair >’)

我没能解决这个问题。 我尝试以多种方式修复这段代码,改变 map和pair中的配对方式

pair<int, string >
pair<int, string &>
pair<int, char *>

错误打印[对我]来说很复杂

#include <iostream>
#include <iterator>
#include <string>
#include <map>
using namespace std;
int main(int argc, char **argv[])
{
map<int, string> science {{101,"physics"},{102,"chemistry"}};

auto itrt = ostream_iterator<pair<int, string > >(cout, ",");

copy(science.begin(), science.end(),itrt);
return 1;
}

预期结果:- 101物理,102化学,

最佳答案

你可以使用

ostream_iterator<pair<int, string > >

仅当您在自己的代码中定义了以下重载

std::ostream& operator<<(std::ostream& out, std::pair<int, std::string> const& p);

标准库不提供这样的重载。

为了使其更通用,您可以重载:

template <typename T1, typename T2>
std::ostream& operator<<(std::ostream& out, std::pair<T1, T2> const& p);

关于c++ - 为什么这个 C++ STL 代码编译失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57702881/

相关文章:

c++ - 如何将较大数字中 0 到 9 的各个数字放入仅包含数字的数组中

c++ - 在 C++11 中绘制 n 个随机值的优雅方法?

c++ - 在运行时确定 std::map/std::set 的内存使用

c++ - c++调用基类的ostream友元函数

c++ - 为什么结构体的 sizeof 不等于每个成员的 sizeof 之和?

c++ - 如何柯里化(Currying) C/C++ 宏?

c++ - 函数 MsiGetProperty() 失败

c++ - 调用带有字符串参数的函数直接与变量

c++ - 返回引用时返回错误

c++ - 如何创建 NVIDIA OpenCL 项目