我有这样的代码:
#include <memory>
#include <map>
struct element {
std::map<std::weak_ptr<int>, int> weights;
bool operator<(const element &a) const { return this->weights < a.weights; }
};
int main() { return 0; }
我想比较这个类的两个实例,但是我得到编译器错误:
/usr/include/c++/4.8/bits/stl_pair.h: In instantiation of ‘constexpr bool std::operator<(const std::pair<_T1, _T2>&, const std::pair<_T1, _T2>&) [with _T1 = const std::weak_ptr<int>; _T2 = int]’:
/usr/include/c++/4.8/bits/stl_pair.h:221:24: error: no match for ‘operator<’ (operand types are ‘const std::weak_ptr<int>’ and ‘const std::weak_ptr<int>’)
{ return __x.first < __y.first
/usr/include/c++/4.8/bits/stl_pair.h:222:23: error: no match for ‘operator<’ (operand types are ‘const std::weak_ptr<int>’ and ‘const std::weak_ptr<int>’)
|| (!(__y.first < __x.first) && __x.second < __y.second); }
/usr/include/c++/4.8/bits/stl_pair.h:222:65: error: body of constexpr function ‘constexpr bool std::operator<(const std::pair<_T1, _T2>&, const std::pair<_T1, _T2>&) [with _T1 = const std::weak_ptr<int>; _T2 = int]’ not a return-statement
|| (!(__y.first < __x.first) && __x.second < __y.second); }
看到no match for operator
了,我添加了以下代码,但没有帮助。
// from boost::weak_ptr
template<typename T, typename U>
bool operator<(const std::weak_ptr<T> &a, const std::weak_ptr<U> &b)
{
return a.owner_before(b);
}
当我尝试以下操作时,错误仍然存在:
- 添加
constexpr
到任何此运算符; - 像这样向地图添加自定义比较器:
std::map<std::weak_ptr<int>, int, std::owner_less<std::weak_ptr<int>>>
.
我可以通过以下方式编译此代码:
- 将运算符 return 语句替换为:
return true
; - 将权重成员的类型更改为不使用
std::weak_ptr
,例如std::map<int, int>
: - 将自定义比较运算符添加到不比较映射但比较每个键和值的类元素。
选项 1. 和 2. 只是为了测试而不是选项;3. 可能,但我想了解为什么会出现此错误并尽可能使用标准库。在我的理解中,它应该编译:std::map
有一个operator<
,它比较内部树,它应该比较pairs<key, data>
,它比较对中的第一个和第二个元素,至少如果提供了一个operator<
for应该工作weak_ptr
。
但它不起作用(至少不适用于 g++ 4.8.{1,2}),因此我的问题是:
- 为什么它不起作用,为什么我会收到此错误消息?
- 如何将两个
maps
与weak_ptr
as 键进行比较?
更新,std::lexicographical_compare
按照 KerrekSB 的建议使用。
我正在尝试比较两个不同的地图。在下面的示例中,映射 m1 和 m2 具有相同的键,但使用此键存储不同的值。如果比较这两个映射,它们应该不相等,应该排序在另一个之前。
#include <memory>
#include <map>
#include <iostream>
typedef std::owner_less<std::weak_ptr<int>> wp_less;
typedef std::map<std::weak_ptr<int>, int, wp_less> wp_map;
bool map_cmp(const wp_map &a, const wp_map &b)
{
return std::lexicographical_compare(
a.begin(), a.end(),
b.begin(), b.end(),
[]( std::pair<std::weak_ptr<int> const, int> const & p,
std::pair<std::weak_ptr<int> const, int> const & q) -> bool
{ return wp_less()(p.first, q.first); });
//{ return wp_less()(p.first, q.first)
// || ( ! (wp_less()(q.first, p.first)) && p.second < q.second); });
}
int main()
{
std::shared_ptr<int> sp_int(std::make_shared<int>(5));
std::weak_ptr<int> wp_int(sp_int);
wp_map m1, m2;
m1[wp_int] = 1;
m2[wp_int] = 2;
std::cout << "m1 < m2=" << map_cmp(m1, m2) << "\nm2 < m1=" << map_cmp(m2, m1);
return 0;
}
如图所示的输出表明两者相等:
m1 < m2=0
m2 < m1=0
但它们不是,通过使用注释比较,结果变为:
m1 < m2=1
m2 < m1=0
所以这给我留下了:
- 我必须做什么才能使默认的词典比较做我想要比较这些对的事情?
- 从问题的原始部分来看,为什么会出现此错误,尤其是导致 constexpr 错误的原因?