black
black

Reputation: 1263

getting certain component of all elements in vector

I have stored some elements of a struct, let's call it myStruct, in a vector. Now I want to get a certain component of this struct of all the elements in my vector.

Is there a possibility to do this fast, without using a for-loop? Is there an equivalent solution for deque?

struct myStruct{
    int a;
    int b;
};

vector<myStruct> vec;

//creating some data and push back to vector
myStruct ms0,ms1;
ms0.a = 5;
ms1.a = 10;             
vec.push_back(ms0);
vec.push_back(ms1);

//now I want to get the component a of ms0 and ms1

Upvotes: 4

Views: 448

Answers (3)

Ziezi
Ziezi

Reputation: 6467

Vectors are sequence containers, more specifically arrays that can change their size dynamically, thus to access all of their elements it will take time proportional to their size, n. Thus the answer to your first question:

Is there a possibility to do this fast, without using a for-loop?

is: No

As for the second question:

Is there an equivalent solution for deque?

Yes, there is and it will look the same as the one posted, with the small difference in the container which instead of vector<myStruct> vec; will be std::deque<int> mydeque;

Upvotes: 1

Julien Lopez
Julien Lopez

Reputation: 1854

You could use two vectors, one storing component a, one storing component b, instead of one vector storing pairs (a, b).

If this doesn't work for you, you can do something like (this is C++11 or higher):

std::for_each(vec.begin(), vec.end(),
[] (myStruct &v) {std::cout << v.a << '\n';} );

But this is not (in terms of complexity) better than a for loop.

Upvotes: 1

Gilson PJ
Gilson PJ

Reputation: 3600

Internally vector uses arrays so you can directly access its elements using [] operator,

eg:

cout<< vec[0].a << vec[1].a;

Upvotes: -1

Related Questions