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


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 的人的索引号?

使用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++中使用迭代器,除非你有充分的理由想要索引。

使用for 循环在向量中搜索

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

使用 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;
}

最新更新