gpt4 book ai didi

c++ - std::ostream_iterator 未找到运算符<<

转载 作者:可可西里 更新时间:2023-11-01 16:34:32 25 4
gpt4 key购买 nike

我已经声明了一个 operator<<对于 std::pair<int, int> :

std::ostream& operator<<(std::ostream& o, const std::pair<int, int>& p) {
o << p.first << p.second;
return o;
}

我想在打印数据时使用这个运算符:

std::vector<std::pair<int, int>> data;
std::copy(data.begin(), data.end(), std::ostream_iterator<std::pair<int, int>>(std::cout, "\n"));

但是编译器说,no match for operator<< ...我做错了什么?

最佳答案

std::copy找不到 operator << 的重载对于 std::pairstd命名空间。没有什么好办法,重载operator <<对于来自 std 的对象算法中的命名空间来自 std命名空间。

您可以使用 std::for_each使用仿函数,它将打印您的值,例如使用 lambda。

std::for_each(data.begin(), data.end(), [](const std::pair<int, int>& p)
{
std::cout << p << std::endl;
});

你不能在 std 命名空间中放置重载,你只能为用户定义的类型添加特化,因为

The behavior of a C++ program is undefined if it adds declarations or definitions to namespace std or to anamespace within namespace std unless otherwise specified

A program may add a template specializationfor any standard library template to namespace std only if the declaration depends on a user-defined typeand the specialization meets the standard library requirements for the original template and is not explicitlyprohibited.

关于c++ - std::ostream_iterator 未找到运算符<<,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20284405/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com