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?
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' );