C++ <algorithm>: 复制地图<A,B> 到库特?

C++ <algorithm>: copy map<A,B> to cout?

本文关键字:gt lt 复制 algorithm C++ 地图      更新时间:2023-10-16

有没有办法使用C++的复制函数从map<A,B>到cout进行复杂的copy

看起来很复杂,因为 map 有多个项目,并且迭代器本身不指向读取数据。

我的意思是类似于我们对矢量所做的:

copy (vector.begin(), vector.end(), ostream<int>(cout," "));

地图的value_type是std::pair<key_type, assoc_type>。若要执行副本,需要提供采用该类型的operator<<。例如,对于map<string, int>,它将是:

std::ostream *operator<<(std::ostream &os, std::pair<std::string, int> const &v) {
    return std::cout << v.first << ":t" << v.second;
}

不过,您通常必须将其放在namespace std中,以便编译器找到它。