Filling a vector of non-integer type using a for loop

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);
	}
}
Last edited on
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#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

    static void 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 (const auto& e: enemies) std::cout << e << ' ';
    std::cout << '\n';
}

Last edited on
> it looks like InitEnemy should be a static function of the class.
¿why?

> filling every member with the data I need
that's the crux of the matter, ¿how are they suppossed to be filled?

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!
Last edited on
but didn't pass by reference

But you've changed it to pass by reference, right? Otherwise it won't actually change the caller's vector.
¿?¿w¿?h¿y¿?n¿¿?o¿t¿?
Yeah, I did now. As a matter of fact, I had done that in other classes' object initializations, but forgot this time.
Topic archived. No new replies allowed.