getting struct member from vector list

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
struct gunType
{
    string name;        //the name of the gun
    float cost;         //the cost of the gun
    int damage;         //how much damage per round gun can do
    bool oneHander;     //is the gun a 1 hander or not
};

guntype shotGun;    //NOTE: sample initialization of each guntype struct
shotGun.name = "Shot gun"; 
shotGun.cost = 125.95; 
shotGun.damage = 18; 
shotGun.oneHander = false;

vector<gunType> gunLIST;
    
gunLIST.push_back(shotGun);  //<- GIVEN: all gun structs were initialized with values
gunLIST.push_back(laserPistol);
gunLIST.push_back(AK);
gunLIST.push_back(nineMilli);


Now how can I access the gunType members from with in the vector gunLIST?
Like how could I print out a list of all the gunType.name?
How could I make a for_each loop to handle it as well?
You can access the vector elements using the overloaded [] operator or the at method. Example:
1
2
gunLIST[0].name
gunLIST.at(0).name;
so print a list of all the gun.names would look like
1
2
3
4
for(int counter = 0; counter < gunList.size(); ++counter)
{
    cout << gunLIST[counter].name << endl;
}
Yes.
A more general solution would be

1
2
3
4
5
6
7
typedef std::vector<gunType> Armory;

Armory gunLIST;
// ... fill out ...

for( Armory::const_iterator i = gunLIST.begin(); i != gunLIST.end(); ++i )
    std::cout << i->name << std::endl;


As this approach does not use operator[] which is defined only for a few
containers. This approach therefore works with any sequence container
with only a change to the typedef, whereas the above works only for
containers that have operator[].

Another solution, equally good:

1
2
3
4
5
6
7
8
#include <algorithm>
#include <boost/lambda/lambda.hpp>

std::vector<gunType> gunLIST;
// ... fill out ...

std::for_each( gunLIST.begin(), gunLIST.end(),
    std::cout << &boost::lambda::_1->*&gunType::name << '\n' );

&boost::lambda::_1->*&gunType::name

what does this process do "literally"
Topic archived. No new replies allowed.