Some Concepts Trip me Up: C++ vector of objects

ImageI’m struggling with a new element of code: vectors. I’ve known about them for some time as people keep suggesting that I use them rather than arrays. One benefit is that vectors are supposed to be more flexible in their size, i.e. you can shrink or expand them as needed while the program is running.

Nevertheless, I am having a terrible time getting my head around these things.

ImageI thought this might be a good place to work out the kinks with some stepwise coding examples (as I learn them myself). As an example, I would like to figure out how to use vectors to handle two problems. The first, simpler, problem is to have a vector of people (i.e. strings) (let’s make them clowns) that we want to stuff into a car and then let them out again, each time resizing the vector and outputting the size of the vector as well as the names of the clowns in the car.

1. empty car (0)

2. pick up Pennywise and John Wayne Gacy (2)

3. Pick up Bozo and Krusty (4)

4. Pick up Ronald McDonald (5)

5. Ronald McDonald gets kicked out (4)

6. All the rest stop for a drink at the Alehouse together (0)

 

As a second example:

Same idea, but this time the vector holds objects (we’ll make them students: each has a string: name and int: grade). Everything else is the same as above

1. empty car (0)

2. pick up Pennywise,98 and John Wayne Gacy,47 (2)

3. Pick up Bozo,78 and Krusty,59 (4)

4. Pick up Ronald McDonald,17 (5)

5. Ronald McDonald gets kicked out (4)

6. All the rest stop for a drink at the Alehouse together (0)

I’m going to work this out myself now, but any input is greatly appreciated.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: