Obtaining a specific component of all elements of the vector

I saved some elements of the structure, let's call it myStructin the vector. Now I want to get a specific component of this structure of all elements in.

Is there any way to do this quickly 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
+4
source share
3 answers

You can use two vectors: one storage component a, one storage component binstead of one vector storing pairs ( a, b).

If this does not work for you, you can do something like this (this is C ++ 11 or higher):

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

( ) , for.

+1

, , , , , n. , :

, for?

: No

:

deque?

, , , , , vector<myStruct> vec; std::deque<int> mydeque;

+1

Internally vector , [],

:

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

All Articles