![](/img/trans.png)
[英]When/How do container data types (string, vector, etc.) in C++ free their dynamically allocated memory?
[英]How do I check for membership in a C++ std::vector, etc.?
我在以下程序中做错了什么?
我想在容器上使用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;
}
const bool operator==(Pair p, Pair q) {return p.x == p.x && q.y == q.y ;}
仔细观察那条线。
此条件始终为真:
const bool operator==(Pair p, Pair q) {return p.x == p.x && q.y == q.y ;}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.