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

person tmp_person;
tmp_person.p_id = 1;
people.push_back(tmp_person);


person tmp_person2;
tmp_person2.p_id = 2;
people.push_back(tmp_person2);


person tmp_person3;
tmp_person3.p_id = 3;
people.push_back(tmp_person3);

How can I find a index number of vector people by the person's id. For example, how can I get a index number of a person who has p_id 2?

유 길재
  • 55
  • 1
  • 4
  • 3
    Does this answer your question? [Return index of struct position in vector](https://stackoverflow.com/questions/41553361/return-index-of-struct-position-in-vector) – Daniel Langr May 28 '20 at 09:11

3 Answers3

1

Use std::find_if to find the element. This returns an iterator to the element. And if you really want to know the index use std:distance:

int id_to_find = 1;

std:size_t found_idx = std::distance(
    std::begin(people),
    std::find_if(std::begin(people), std::end(people),
                [=] (const person& p) { return p.p_id == id_to_find; })
    );

But you should really use iterators in C++ unless you have a good reason to want indexes.

bolov
  • 72,283
  • 15
  • 145
  • 224
0

Search in the vector using for loop.

for(int i=0;i<people.size();i++){
    if(people[i].p_id == 2){
        return i
        break;
    }
}
Vinay Somawat
  • 639
  • 14
  • 23
0

Solution using find_if

#include <iostream>     // std::cout
#include <algorithm>    // std::find_if
#include <vector>       // std::vector
int val=2;
struct person{
    int p_id;
};
bool isValue (struct person i) {
  return ((i.p_id)==val);
}

int main () {
  std::vector<struct person> people;

  person tmp_person;
  tmp_person.p_id = 1;
  people.push_back(tmp_person);


  person tmp_person2;
  tmp_person2.p_id = 2;
  people.push_back(tmp_person2);


  person tmp_person3;
  tmp_person3.p_id = 3;
  people.push_back(tmp_person3);

  std::vector<person>::iterator it = std::find_if (people.begin(), people.end(), isValue);
  std::cout << "The index of value is " << it-people.begin() << '\n';


  return 0;
}
Yashasvi.G
  • 43
  • 7