[英]std::find how does it work? operator==
如果我有課
class Point
{
public:
Point() {}
Point(int _col, int _row) : row(_row), col(_col) {}
int row, col;
};
如何使用std :: find()檢查該點是否已經在向量中? 我必須重載operator ==嗎?
我正在嘗試這樣做
#include <algorithm>
if(std::find(v.begin(), v.end(), x) != v.end()) {
/* v contains x */
} else {
/* v does not contain x */
}
我在Stack Overflow上找到的幾乎所有答案都建議使用find檢查對象是否在std::vector
但是它們都不能解釋它是比較對象的指針還是對象的實際值。
C ++標准(草案N3242)(在第25.2.5節[alg.find]中)說std::find
:
返回 :范圍為
[first,last)
的第一個迭代器i
,其符合以下條件:*i == value
[...]。 如果找不到這樣的迭代器,則返回last
。
您是否根據對象的值或地址進行搜索的問題取決於operator==
的實現方式。 簡單的答案是: std::find
將迭代器返回到operator==
返回true的對象。
通常,這只是基於值的比較(因為通常使用operator==
來比較兩個對象的值),因此通常應該期望std::find
在范圍內搜索您提供的值(而不是您提供的對象的地址)。
可以實現operator==
,使其基於address進行比較 ,如下所示:
bool operator==(const Point& left, const Point& right) {
return &left == &right;
}
使用該operator==
將比較地址,因此std::find
將搜索與您提供的地址相同的對象。 但是,像這樣實現operator==
通常是一個壞主意。 大多數人會這樣實現operator==
:
bool operator==(const Point& left, const Point& right) {
return left.row == right.row && left.col == right.col;
}
當與std::find
,它將根據Point
的值比較Point
。
除非您的類型是POD的基本類型,否則您將需要提供一個等於或不等於成員的相等函數。
std::find
有兩個基本版本,一個假定相等運算符,另一個使用您提供的相等函數。
我建議您將operator==
和operator<
添加到將被比較相等性或有序的任何類。
這是您課程的更新版本:
class Point
{
int x; // These are private by default.
int y;
public:
Point(int new_x, int new_y) : x(new_x), y(new_y)
{ ; }
bool operator==(const Point& p) const
{
return (x == p.x) && (y == p.y);
}
};
成員方法operator==
允許進行比較,而不會向朋友或公眾公開這些值。
如果要使用獨立式比較功能,則需要將值公開或將該功能設為朋友:
class Point
{
int x; // These are private by default.
int y;
public:
Point(int new_x, int new_y) : x(new_x), y(new_y)
{ ; }
friend bool operator==(const Point& a, const Point& b);
};
bool operator==(const Point& a, const Point& b)
{
return (a.x == b.x) && (a.y == b.y);
}
如果要對std::find
使用獨立功能,則示例為:
std::vector<Point> point_container;
//...
Point p;
std::vector<Point>::const_iterator iter;
iter = std::find(point_container.begin(), point_container.end(),
p,
Equal_Points);
其中Equal_Points
是一個獨立功能,可以比較兩個Point的成員。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.