gpt4 book ai didi

c++ - 如何检查 C++ std::vector 等中的成员资格?

转载 作者:太空宇宙 更新时间:2023-11-04 15:08:15 26 4
gpt4 key购买 nike

我在下面的程序中做错了什么?

我想在容器上使用 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 ;}

仔细看那条线。

关于c++ - 如何检查 C++ std::vector 等中的成员资格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8529544/

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