让我们看代码:
struct tmp {
int a;
std::vector <second_struct> b;
}
struct second_struct {
int x;
int y;
}
//main.cpp
int main {
std::vector<tmp> test;
(...); //push data to test
}
所以当我推送数据进行测试时,在第二个函数中我想获得 vector
来自此 vector 的“b”'test'
.并通过 a 找到 vector b;
(即我有 int a
和 std::vector<tmp> test;
,没有 std::vector <second_struct> b;
(来自 vector 测试)并想得到它。( vector 测试是一个大数组,所以我需要以最快的速度完成它并且使用很少的功率)
怎么做?(我想 std::map 会更好?但如果你告诉我是,请告诉我如何在 std::Vector 中做到这一点)
最佳答案
遍历test
vector 检查是否tmp::a
member 等于你的 int a
.如果是这样,你有你的 vector<second_struct> b
for (int i=0;i<test.size();i++) {
if (test[i].a == a) {
// do whatever you need to do with test[i].b
break;
}
}
附言 map 会更容易,只是
std::map<int, std::vector<second_struct>> map;
//insert data
std::vector<second_struct> b = map[a]; //assuming it's a that you're looking for
关于c++ - 在具有结构的 vector 中获取项目位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25217858/