涉及std :: equal_range的无效操作数编译器错误

时间:2018-02-21 01:46:28

标签: c++ compiler-errors c++14

使用以下模板实现间隔图

template<class K, class V>
intervalMap{
public:
intervalMap(V const&);
public:
void assign(K const&, K const&, V const&);
private:
std::map<K,V>m_map;
};

成员函数assign()中的以下代码段:

template<class K, class V> void intervalMap::assign(
                                             K const& keyBegin, 
                                             K const& keyEnd,
                                             V const& val
                                            ){

            auto begin = m_map.find(keyBegin);
            auto end = m_map.find(keyEnd);

            auto p = std::equal_range(begin,end,val);

}

以及main()

中的以下实例化
intervalMap<unsigned int, char> iMap('A');
iMap.assign(1,2,'A');

以下编译错误结果:

In file included from main.cpp:1:
In file included from ./code.hpp:4:
In file included from /Library/Developer/CommandLineTools/usr/
include/c++/v1/map:442:
In file included from /Library/Developer/CommandLineTools/usr
/include/c++/v1/__tree:18:
/Library/Developer/CommandLineTools/usr/include/
c++/v1/algorithm:701:71: 
error: invalid operands to binary expression 
('const std::__1::pair<const unsigned int, char>' and 'int')
    bool operator()(const _T1& __x, const _T2& __y) 
const {return __x < __y;}
              ~~~ ^ ~~~

该错误与以下源代码段有关(在错误日志中突出显示):

./code.hpp:120:18: note: in instantiation of function 
template specialization 'std::__1::equal_range
<std::__1::__map_iterator
<std::__1::__tree_iterator
<std::__1::__value_type
<unsigned int, char>, 
std::__1::__tree_node
<std::__1::__value_type
<unsigned int, char>, 
void *> *, long> >, 
char>' 
requested here
        auto p = equal_range(begin,end,val);
                 ^
./code.hpp:205:10: note: 
in instantiation of member function 
'interval_map<unsigned int, char>::assign' 
requested here
    iMap.assign(1,2,'A');

欣赏建议。

1 个答案:

答案 0 :(得分:0)

错误是由于比较了由V表示的std :: pair和模板变量,在本例中为char。为避免这种情况,您可以使用如下的服装谓词。

template<class K, class V>
class intervalMap{
public:
intervalMap(V  val)
{
   v = val;
}
public:
void assign(K const a, const K  b,  const V c);

private:
V v;
std::map<K,V> m_map;

};
template<class K, class V>
struct comp
{
    bool operator()(std::pair<K, V> a, V b)
    {
        return a.second < b;
    }
    bool operator()(V a, std::pair<K, V> b)
    {
        return a < b.second;
    }
};

template<class K, class V>
void intervalMap<K, V>::assign(const K  keyBegin, const K  keyEnd, const V  
val)
{
    auto begin = m_map.find(keyBegin);
    auto end = m_map.find(keyEnd);


    auto p = std::equal_range(begin, end, val,comp< K,  V>());
}