1

I have a vector like below.

struct Personel {
    uint16_t personelId;
    uint8_t age;
}

std::vector<Personel> Personels;

Imagine adding 1000 elements as below.

Personel personel1;
personel1.personelId = 1;
personel1.age = 26;
Personels.push_back(personel1);
.
.
.
Personel personel1000;
personel1000.personelId = 1000;
personel1000.age = 42;
Personels.push_back(personel1000);

As it is understood from the code, personelId will be unique. Without iterating each element with for and comparing, How can I get index according to personelId.

Below code not working: Because int not Personel

auto match = std::find(Personels.begin(), Personels.end(), 596);
int index = std::distance(Personels.begin(), match); //must return 596
Qwe Qwe
  • 399
  • 4
  • 13
  • unfortunately this question is better in terms of providing something more close to a [mcve] compared to the duplicate question. Anyhow, as you already got answers I thought I doesnt hurt to close as duplicate. Maybe someone will find a better one – 463035818_is_not_an_ai Mar 12 '20 at 11:18

2 Answers2

3

For find you need to pass value of the same type as vector value. The one of ways is to define oprator== for Personel, create pesonal with target ID and use find. The other is to use find_if with lambda:

auto match = std::find_if(Personels.begin(), Personels.end(), [] (const Personel& v) {return v.personelId ==  596});
int index = std::distance(Personels.begin(), match); 

Or, you may use old good for )))

Askold Ilvento
  • 1,405
  • 1
  • 17
  • 20
  • Does Find_if have an advantage in speed? – Qwe Qwe Mar 12 '20 at 11:06
  • @QweQwe algorithms arent faster than handwritten loops. They are as fast as handwritten loops. You can find a possible implementation here https://en.cppreference.com/w/cpp/algorithm/find. The advantage is not speed, but readability and less opportunities to make mistakes – 463035818_is_not_an_ai Mar 12 '20 at 11:20
  • 1
    Compare with what? Compare with passing to `find` structure, `find_if` should probably be slight faster because of less overhead, but it is negligible. To my mind `distance` is very slow, difference is faster (match - Personels.begin()), and `for` is faster in your case because you do not need to recount iterator to index. – Askold Ilvento Mar 12 '20 at 11:24
  • @AskoldIlvento iterate through for – Qwe Qwe Mar 12 '20 at 11:29
2

As you noticed, std::find will not work here, because you want to compare only based on the personel id, ignoring all other fields.

This is exactly what std::find_if is for. It has an additional parameter for supplying a predicate to be used during the search. Simply call find_if with a predicate that checks the personel id of the given element for the one you are looking for.

ComicSansMS
  • 51,484
  • 14
  • 155
  • 166