【问题标题】:why does this C++ STL code fail in compilation为什么这个 C++ STL 代码编译失败
【发布时间】:2019-08-30 02:25:22
【问题描述】:

编译错误

/usr/include/c++/7/bits/stream_iterator.h:199:13: 错误:不匹配 ‘operator>::ostream_type {aka std::basic_ostream}' 和 '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 化学,

【问题讨论】:

  • 我怀疑你得到的不仅仅是一个错误。这是使用 STL 的副作用(意大利面条错误消息喷出......起初可能有点难以确定......它会变得更好)

标签: c++


【解决方案1】:

你可以使用

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);

【讨论】:

  • 或更一般的template &lt;typename T1, typename T2&gt; std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, std::pair&lt;T1, T2&gt; const&amp; p)
  • @Caleth,确实如此。
【解决方案2】:

我认为这应该可行... (因为复制和 ostream_iterator 不起作用)

#include <iostream>
#include <iterator>
#include <string>
#include <map>
#include <algorithm>
#include <sstream>
using namespace std;
typedef std::pair<int ,string> PairII;

string to_s(PairII const & pii) {
    stringstream ss;
    ss << pii.first << " " << pii.second ;
    return ss.str();
}
int main()
{
    map<int, string> science {{101,"physics"},{102,"chemistry"}};
    std::transform(science.begin(), science.end(),
    std::ostream_iterator<std::string>(cout, " , "), to_s);

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 2011-01-22
    • 2015-05-29
    相关资源
    最近更新 更多