Thomas Banderas
Thomas Banderas

Reputation: 1739

Take item position in vector with structure

Let see code:

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
}

So when i push data to test, in second function i want to get vector "b" from this vector 'test'. And find vector b by a;

(i.e I have int a and std::vector<tmp> test; , dont have std::vector <second_struct> b;(from vector test) and want to get it. (vector test is a big array, so i need to do it fastest and using little power )

How to do that? (i suppose std::map will be better? But if you tell me yes, tell me too how to do that in std::Vector)

Upvotes: 0

Views: 58

Answers (2)

yasen
yasen

Reputation: 1260

The most straightforward approach is to use map (or unordered_map in C++11). Hope this full example helps:

#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;
}

Upvotes: 0

prajmus
prajmus

Reputation: 3271

Loop through test vector checking if tmp::a member is equal to your int a. If so, you have your 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;
    }
}

P.S. map would be easier, just

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

Upvotes: 1

Related Questions