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/