gpt4 book ai didi

c++ - std::map 和 std::pair 的问题

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

我想执行一个小程序来测试一些东西

#include <map>
#include <iostream>
using namespace std;

struct _pos{
float xi;
float xf;

bool operator<(_pos& other){

return this->xi < other.xi;
}
};

struct _val{

float f;
};

int main()
{
map<_pos,_val> m;

struct _pos k1 = {0,10};
struct _pos k2 = {10,15};

struct _val v1 = {5.5};
struct _val v2 = {12.3};

m.insert(std::pair<_pos,_val>(k1,v1));
m.insert(std::pair<_pos,_val>(k2,v2));

return 0;
}

问题是当我尝试编译它时,出现以下错误

$ g++ m2.cpp -o mtest
In file included from /usr/include/c++/4.4/bits/stl_tree.h:64,
from /usr/include/c++/4.4/map:60,
from m2.cpp:1:
/usr/include/c++/4.4/bits/stl_function.h: In member function ‘bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = _pos]’:
/usr/include/c++/4.4/bits/stl_tree.h:1170: instantiated from ‘std::pair<typename std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator, bool> std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_insert_unique(const _Val&) [with _Key = _pos, _Val = std::pair<const _pos, _val>, _KeyOfValue = std::_Select1st<std::pair<const _pos, _val> >, _Compare = std::less<_pos>, _Alloc = std::allocator<std::pair<const _pos, _val> >]’
/usr/include/c++/4.4/bits/stl_map.h:500: instantiated from ‘std::pair<typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_Select1st<std::pair<const _Key, _Tp> >, _Compare, typename _Alloc::rebind<std::pair<const _Key, _Tp> >::other>::iterator, bool> std::map<_Key, _Tp, _Compare, _Alloc>::insert(const std::pair<const _Key, _Tp>&) [with _Key = _pos, _Tp = _val, _Compare = std::less<_pos>, _Alloc = std::allocator<std::pair<const _pos, _val> >]’
m2.cpp:30: instantiated from here
/usr/include/c++/4.4/bits/stl_function.h:230: error: no match for ‘operator<’ in ‘__x < __y’
m2.cpp:9: note: candidates are: bool _pos::operator<(_pos&)
$

我认为在键上声明运算符< 可以解决问题,但它仍然存在。

有什么问题吗?

提前致谢。

最佳答案

问题是这样的:

bool operator<(_pos& other)

应该是这样的:

bool operator<(const _pos& other) const {
// ^^^^ ^^^^^

没有第一个const , 比较的右侧( b 中的 a < b )不能是 const , 因为没有 const该函数可以修改其参数。

没有第二个const , 比较的左侧( a 中的 a < b )不能是 const , 因为没有 const该函数可能会修改 this .

在内部,映射的键总是 const .


应该注意的是,您应该更喜欢使用非成员函数。也就是说,自由函数更好:

bool operator<(const _pos& lhs, const _pos& rhs)
{
return lhs.xi < rhs.xi;
}

在与您的类相同的命名空间中。 (对于我们的例子,就在它下面。)


顺便说一下,在 C++ 中,不需要在结构类型变量的声明前加上 struct 前缀。 .这是完美的,并且是首选:

    _pos k1 = {0,10};
_pos k2 = {10,15};

_val v1 = {5.5};
_val v2 = {12.3};

(虽然你的类型名称是以非正统的方式命名的。:P)


最后,您应该更喜欢 make_pair配对的效用函数:

    m.insert(std::make_pair(k1,v1));
m.insert(std::make_pair(k2,v2));

它使您不必写出该对的类型,并且通常更易于阅读。 (特别是当出现较长的类型名称时。)

关于c++ - std::map 和 std::pair 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2643010/

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