transfer from struct array to vector

I had this nice array-object named army[] from a struct named soldier, which included some names with their respective random attributes. I decided that if one of my soldiers would get killed it would be easier to use a vector with the "erase" command to remove the deadman from my list.

Initially it looked something like this when I placed soldiers into my army[]:

for (count=1; count<=10; count++) {
attribute[0] = rand() % 10;
...
army[count].name = soldiers[count];
army[count].str = attribute[0];
...
}

Now, how do I this sort of thing in "vector form".
I've been messing around with vector::push_back iterators with no success;
made it in without errors using a vector::at, but then it crashed at run-time.

I don't know if I am making myself clear enough, but perhaps someone understands what I mean.
Thanks
Simple example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <vector>

struct Soldier
{
	int health;
	int ID;
};

int main()
{
	std::vector<Soldier> army;

	for( int i = 0; i < 10; i++ )
	{
		Soldier temp;
		temp.health = 100;
		temp.ID = i;
		army.push_back(temp);
	}

	// Accessing elements through the [] operator
	for( unsigned int i = 0; i < army.size(); i++ )
	{
		std::cout << "Soldier ID = " << army[i].ID << ", health = " << army[i].health << std::endl;
	}

	// Using an iterator to access the elements inside the vector
	std::vector<Soldier>::iterator iter;
	for( iter = army.begin(); iter != army.end(); iter++ )
	{
		std::cout << "Soldier ID = " << iter->ID << ", health = " << iter->health << std::endl;
	}

	return 0;
}
Thanks!

That worked well enough. I'm not sure why I couldn't get it to work before.

Now I just have to spend the rest of the day fixing errors and figure out how to kill off my soldiers one-by-one.
Any errors or problems you have - feel free to post them up with source code.
Well... My vector::erase idea might not be the best after all. If I kill a wolf in a certain part of my map it is erased from its spot in the vector and the bear formerly one spot "higher" in the vector and in the other corner of the map suddenly takes his place in the vector and on the map. So who knows how my army vector is doing.

What is the best method of removing items from a list?
Use erase. I'm not really sure what your problem is though.
I found it... I need to spend more time reading the introductions, not just look at the example. So I guess there are also these things out there called deques and lists, where lists are the most useful in removing an item from a stack without others falling down into its empty space.
Thanks anyway.
Ah, yeah, if you want your iterators/pointers to remain valid, on insertion/delete, you would use a list.
Topic archived. No new replies allowed.