如何通过向量中的结构ID获取索引号

时间:2020-05-28 09:03:14

标签: c++ vector

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);

如何通过人的ID查找向量的索引号。 例如,如何获得p_id为2的人的索引号?

3 个答案:

答案 0 :(得分:1)

使用std::find_if查找元素。这将向元素返回一个迭代器。如果您真的想知道索引,请使用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; })
    );

但是除非您有充分的理由想要索引,否则您应该在C ++中真正使用迭代器。

答案 1 :(得分:0)

使用 for循环在向量中

搜索

for(int i=0;i<people.size();i++){
    if(people[i].p_id == 2){
        return i
        break;
    }
}

答案 2 :(得分:0)

使用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;
}
相关问题