c++ - 从作用于 map 的算法调用的仿函数可以接受 pair<K, V> 而不是 value_type 吗?

标签 c++ standards-compliance const-correctness

我试图编写一个简短的函数来反转 std::map<K, V> (我知道 boost.bimap,这是为了自学),令我惊讶的是,GCC 4.4 接受的带有 -pedantic -ansi 设置的代码被 SunCC(5.8,从 2005 年开始)拒绝为 const-incorrect .

value_typestd::pair<const K, V> , SunCC 坚持要我对我的 K 进行 const-qualify|输入传递给 transform() 的函数的参数和 for_each() , 以及要传递给 std::inserter 的返回值类型,据我所知,这可能是对的?哪个编译器符合标准?

#include <iostream>
#include <iterator>
#include <map>
#include <string>
#include <algorithm>
template<typename K, typename V>
std::pair<V, K> flip_pair(const std::pair<K, V>& p) // GCC/MSVC
//std::pair<const V, K> flip_pair(const std::pair<const K, V>& p) // SunCC
{
     return std::make_pair(p.second, p.first); // GCC/MSVC
//     return std::pair<const V, K>(p.second, p.first); // SunCC
}
template<typename K, typename V>
std::multimap<V, K> invert_map(const std::map<K, V>& in)
{
     std::multimap<V, K> out;
     transform(in.begin(), in.end(), std::inserter(out, out.begin()),
               flip_pair<K, V>);
     return out;
}
void print_pair(const std::pair<int, std::string>& p) // GCC/MSVC
//void print_pair(const std::pair<const int, std::string>& p) // SunCC
{
        std::cout << p.first << '\t' << p.second << '\n';
}
int main()
{
     std::map<std::string, int> map;
     map["foo"] = 1; map["bar"] = 2; map["baz"] = 3;
     std::multimap<int, std::string> revmap = invert_map(map);
     for_each(revmap.begin(), revmap.end(), print_pair);
}

最佳答案

Visual C++ 和 g++ 是正确的;这段代码(带 flip_pair<K, V>()const std::pair<K, V>& )没问题。

内部 transform , flip_pair<K, V>正在被调用。由于传递给该函数的对象是 pair<const K, V> , pair<K, V> 类型的临时对象被创建( pair 有一个转换构造函数,如果 .first.second 类型是可转换的,它允许您将一对类型转换为另一对类型)。

这个临时传递给flip_pair<K, V>() ,利用 const 引用可以绑定(bind)到临时引用这一事实。

关于c++ - 从作用于 map 的算法调用的仿函数可以接受 pair<K, V> 而不是 value_type 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3857716/

相关文章:

c++ - 有没有办法通过 'int' 而不是 'greater/lesser than' 来定义 '=' ?

c++ - 从指针到数组的类型转换

c++ - 函数原型(prototype)中的不同参数名称

c++ - 从源代码构建 Qt 时,我可以制作或指定哪些部分?

c++ - 什么时候在空实例上调用成员函数会导致未定义的行为?

c# - C# 中的 "const correctness"

unit-testing - URL解析测试套件

c++ - friend 应该在嵌套类中传递吗?

c - C 中的泛型编程 - void*- const-correctness

c++ - 这段代码在 C++ 中合法吗