I've got a function that initializes objects of Enemy class (just once), expanding the vector of <Enemy> class type. A for loop doesn't work, however, as it tries inserting integers which are of the wrong type. What could I do in this case to fill the vector automatically with generic members? The only solution I can see at the moment is declaring the objects manually (which I need just 15, but that is subject to change, at run-time also) and iterating through the vector, filling every member with the data I need, but that is far from perfect. I wonder if this approach would work with a dynamic array?
1 2 3 4 5
void Enemy::InitEnemy(std::vector<Enemy> enemy){
for (int i = 0; i < size; i++) {
enemy.push_back(i);
}
}
I think we need to see the rest of the class. But from what you've shown it looks like InitEnemy should be a static function of the class. Also, you presumably want to pass the vector by reference. And if you want to create "Enemy"'s from integers then you need a constructor that does that.
#include <iostream>
#include <vector>
class Enemy {
int n; // whatever an Enemy contains
public:
Enemy(int n) : n(n) {} // However you construct an Enemy from an int
staticvoid InitEnemyVector(std::vector<Enemy>& enemies, int size) {
for (int i = 0; i < size; i++)
enemies.push_back(i);
}
friend std::ostream& operator<<(std::ostream& os, const Enemy& e) {
return os << e.n; // However you output an Enemy
}
};
int main() {
std::vector<Enemy> enemies;
Enemy::InitEnemyVector(enemies, 15);
for (constauto& e: enemies) std::cout << e << ' ';
std::cout << '\n';
}
I think we need to see the rest of the class. But from what you've shown it looks like InitEnemy should be a static function of the class. Also, you presumably want to pass the vector by reference. And if you want to create "Enemy"'s from integers then you need a constructor that does that.
Woah man, that's all I had to do - add an integer as a parameter of the constructor! By the way, I had made it static, but hadn't passed by reference. Thanks a lot!