Call function for each vector element

Hello,

I am programming a game. I achieved to program a vector of enemy objects "std::vector <Character> Enemies;". For each enemy object element int strength, int skill and int life is defined.
So far my program works. The object vector is initialised correctly and I can work with it.
I have a printCharacter() function which prints the character stats to the console.

It works with 6 enemy objects:
1
2
3
4
5
6
7
8
9
10
11
//Print function of class Character
void Character::printCharacter() 
{
std::cout << characterType << " " << characterName 
<< " has: Strength: " << strength << "; Skill: " << skill 
<< "; Life: " << life << std::endl;
}

//Function to print the object vector within upper class "Menu":
for (int i = 0; i < 6; i++) Enemies[i].printCharacter();
//Enemy vector Enemies is created in Menu class 


The problem is of course the for loop up to 6 as I want to use the vector for different number of enemies. I tried the following code at the same position as the loop above, but it states that "printChracter() is undefined". Also "Character::printCharacter()" does not work.
1
2
3
4
5
std::for_each(Enemies.begin(), Enemies.end(), printCharacter());

// I also tried:
for (auto i = Enemies.begin(); i != Enemies.end(); i++) Enemies.at(i).printCharacter())
//But here I do not understand how to combine the at(i) with the printCharacter() 


Could someone please help?
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// using indices
for (std::size_t i = 0; i < Enemies.size(); i++)
{
	Enemies[i].printCharacter();
}

// using iterators
for (std::vector<Character>::iterator enemy = Enemies.begin(); enemy != Enemies.end(); ++enemy)
{
	enemy->printCharacter();
}

// using range-based for loop
for (Character& enemy : Enemies)
{
	enemy.printCharacter();
}

// using algorithms
std::for_each(Enemies.begin(), Enemies.end(), [](Character& enemy)
{
	enemy.printCharacter();
});
Last edited on
Note: Algorithms, such as for_each, take a function object.
The [](Character& enemy) { enemy.printCharacter(); } is a lambda closure. Syntax that was added in C++11.
Lambda is a function object.
Hm, it was easier than expected. Thanks a lot.
I prefer the index function.
Since you did ask about the at():
1
2
3
4
5
// using indices
for (std::size_t i = 0; i < Enemies.size(); i++)
{
	Enemies.at(i).printCharacter();
}


The vector::at() automatically checks whether n is within the bounds of valid elements in the vector, throwing an out_of_range exception if it is not (i.e., if n is greater than, or equal to, its size). This is in contrast with member operator[], that does not check against bounds.

http://www.cplusplus.com/reference/vector/vector/at/
http://www.cplusplus.com/reference/vector/vector/operator[]/
Topic archived. No new replies allowed.