STL list中remove()使用

问题描述

今天在使用 STL list 的 remove() 函数时候出现了一个错误。相关代码如下:

typedef struct _POS {
    int x;
    int y;
} POS;

list<POS> avail;
avail.push_back(...);
....
avail.remove(next);  //这里编译错误

出现的错误信息如下:

note:   '_POS' is not derived from 'const std::__cxx11::match_results<_BiIter, _Alloc>'
    if (*__first == __value)
        ~~~~~~~~~^~~~~~~~~~

问题原因

因为找不到 == 这个对应的操作符,也就是说没有重载结构体的 == 操作符导致了错误。

解决方法

重载 == 操作符,使之可以比较结构体。修改后代码如下:

typedef struct _POS {
    int x;
    int y;
} POS;

bool operator== (const POS &t1, const POS &t2) {
    return (t1.x==t2.x&&t1.y==t2.y);
}
发布了220 篇原创文章 · 获赞 229 · 访问量 106万+

猜你喜欢

转载自blog.csdn.net/justidle/article/details/104754177