我在做什麼錯在下面的程序?如何檢查C++ std :: vector等的成員身份?
我想在容器上使用std::find()
來決定它是否包含給定的元素。下面的程序適用於空容器,但不適用於具有元素的容器。
#include <iostream>
#include <vector>
#include <cassert>
struct Pair {int x,y;};
const bool operator==(Pair p, Pair q) {return p.x == p.x && q.y == q.y ;}
typedef std::vector<Pair> p_containr_t;
int main (int argc, char * const argv[]) {
const Pair start_p = {1,2};
const Pair second_p = {3,4};
const Pair other_p = {5,6};
p_containr_t v;
p_containr_t::iterator where;
where = std::find(v.begin(),v.end(),other_p);
assert(where == v.end());
std::cout << "OK for empty\n"; // Program reaches here.
v.push_back(start_p);
where = std::find(v.begin(),v.end(),other_p);
assert(where == v.end()); // This assertion fails.
std::cout << "OK for first element\n";
v.push_back(second_p);
where = std::find(v.begin(),v.end(),other_p);
std::cout << "OK for second element\n"; // Fails too (if I edit above).
return 0;
}
我想刪除的問題。答案很好。如果我們是結對編程,我不認爲我會犯這個錯誤。問題是否會幫助其他人? – 2015-07-26 09:23:10