1

I'm trying to use the std::find() function on a std::vector. Why does this code bring up an error, and how can I fix this?

struct person_id{
    int p_id;
};
std::vector<person_id> people;

person_id tmp_person;
tmp_person.p_id = 5;
people.push_back(tmp_person);

if(std::find(people.begin(), people.end(), 5) != people.end()) {
    cout<<"Contain"<<endl;
} else {
    cout<<"Not Contain"<<endl;           
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
유 길재
  • 55
  • 1
  • 4

2 Answers2

3

You need to add constructor and operator == to fix the compiler error

#include <algorithm>
#include <vector>
#include <iostream>
struct person_id{
    person_id() = default;
    person_id(int id) : p_id (id) {}

    bool operator==(const person_id& other) { return p_id == other.p_id; }
    int p_id;
};
using std::cout;
using std::endl;

int main(int argc, char* argv[]) {
    std::vector<person_id> people;

    person_id tmp_person;
    tmp_person.p_id = 5;
    people.push_back(tmp_person);

    if(std::find(people.begin(), people.end(), 5) != people.end()) {
        cout<<"Contain"<<endl;
    } else {
        cout<<"Not Contain"<<endl;           
    }
    return 0;
}
  • constructor is used to implicitly convert 5(int type) into struct person_id
  • operator== is required by the std::find function

Check it here: https://coliru.stacked-crooked.com/a/437f4ec26bbc7995

prehistoricpenguin
  • 6,130
  • 3
  • 25
  • 42
2

Your vector is the container of type person_id, you search using an int value. How should compiler know that the integer literal 5 shall be compared with the p_id field?

The simple solution is to have a vector<int>: why do you need that struct? If you still need that type, define the comparison operator or conversion operator... There are many ways to implement this, give us more details.

Dmitry Kuzminov
  • 6,180
  • 6
  • 18
  • 40
  • I am new to c++ so confusing.... do you mean I should change struct to int?? What are the ways that if I want to keep in struct? – 유 길재 Jan 16 '20 at 03:43
  • The easiest thing to do is probably searching for `person_id{5}` instead of `5` – Indiana Kernick Jan 16 '20 at 03:46
  • 1
    The "proper" way to do this would be to explicitly compare `p_id` with `5` using `find_if` – Indiana Kernick Jan 16 '20 at 03:48
  • You should understand the task. If you plan to bring more sense to the entity `Person`, you may add more operations. You should hide the `p_id` field using the `private` access modifier to prevent unintentional access, and expose the `public` operations, etc. Overall that is the question of the task, not of the language. – Dmitry Kuzminov Jan 16 '20 at 03:48
  • 1
    @Kerndog73 The `person_id::p_id` already looks like a tautology, so there is no proper way. – Dmitry Kuzminov Jan 16 '20 at 03:53