C++ 在具有结构的向量中获取项目位置

C++ 在具有结构的向量中获取项目位置,c++,c++11,vector,C++,C++11,Vector,让我们看看代码: 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 } struct tmp{ INTA; std::载体b; } 第二结构{ int x; int-y; } //

让我们看看代码:

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
}
struct tmp{
INTA;
std::载体b;
}
第二结构{
int x;
int-y;
}
//main.cpp
int main{
病媒试验;
(…);//将数据推送到测试
}
所以,当我将数据推送到测试时,在第二个函数中,我想从这个向量
'test'
中得到
向量
“b”。用a求向量b

(也就是说,我有
inta
std::vector test;
,没有
std::vector b;
(来自vector test)并且想要得到它。(vector test是一个大数组,所以我需要以最快的速度和很小的功耗来完成它)


如何做到这一点?(我想std::map会更好?但如果你告诉我是的,也告诉我如何在std::Vector中做到这一点)

循环通过
测试
向量检查
tmp::a
成员是否等于
inta
。如果是这样,你就有了
向量b


for(int i=0;i最简单的方法是使用C++11中的
map
(或
unordered_map
)。希望这个完整的示例有助于:

#include <map>
#include <vector>
#include <iostream>

struct str {
    str(int _x, int _y) : x(_x), y(_y) {}
    int x, y;
};

std::map<int, std::vector<str> > test;

int main() {
    std::vector<str> vec;
    for (int i = 0; i < 100; ++i) {
        vec.clear();
        vec.push_back(str(i, 2 * i));
        vec.push_back(str(i + 1, i + 2));
        test[i] = vec;
    }
    std::vector<str> result;
    // get some element
    result = test[10];
    std::cout << "Found at position 10:\n";
    for (int i = 0; i < result.size(); ++i)
        std::cout << result[i].x << ' ' << result[i].y << '\n';
    return 0;
}
#包括
#包括
#包括
结构str{
str(int x,int y):x(x),y(y){
int x,y;
};
标准:map试验;
int main(){
std::vec;
对于(int i=0;i<100;++i){
向量清除();
向量推回(str(i,2*i));
向量推回(str(i+1,i+2));
试验[i]=vec;
}
std::向量结果;
//得到一些元素
结果=试验[10];
标准::cout
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
#include <map>
#include <vector>
#include <iostream>

struct str {
    str(int _x, int _y) : x(_x), y(_y) {}
    int x, y;
};

std::map<int, std::vector<str> > test;

int main() {
    std::vector<str> vec;
    for (int i = 0; i < 100; ++i) {
        vec.clear();
        vec.push_back(str(i, 2 * i));
        vec.push_back(str(i + 1, i + 2));
        test[i] = vec;
    }
    std::vector<str> result;
    // get some element
    result = test[10];
    std::cout << "Found at position 10:\n";
    for (int i = 0; i < result.size(); ++i)
        std::cout << result[i].x << ' ' << result[i].y << '\n';
    return 0;
}