Hey all.

I don't have any experience with vectors so I'm looking for a little guidance. I don't want the answer, just a direction to take. I've looked up vectors on cplusplus.com but I couldn't understand exactly how they work in order to code them into my program.

Here's my problem.

My program takes numeric user guesses and compares them to a random generated number. If they are wrong, I want to store their guess in an array and output the numbers they've already guessed when the program tells them to guess again.

<random number = 5>
"Take a guess"
<user guesses 6>
"Try again"
"You've guessed: | 6 |"
<user guesses 2>
"Try again"
"You've guessed: | 6 | 2 |"
<user guesses 5>

make any sense?
I don't know how to make the vector an unknown size that can grow and be reset once the random number is reset/they start the game again. I also don't know how to add to the array/vector. I've found .assign() but can't figure out how to use it properly. I've only found it takes a value and repeats it a given number of times.

I'm pretty sure I can figure out how to get the data out just fine with a loop. I've very much new to C++ so I hope I make sense.

Edited by SacredFootball: spelling

6 Years
Discussion Span
Last Post by VernonDozier

On the site you visited, look up vector::push_back and vector::clear

Edited by Fbody: n/a


Here is an example on how to grow vectors :

int main(){
 std::vector<int> numbers;
 //input 10 numbers from user
 for(int i = 0; i < 10; ++i){
   int input = 0;
   cin >> input;
   numbers.push_back( input );
 return 0;

The whole beauty of vectors is that you don't have to handle any of the memory management. All the sizing and resizing is done for you when you add and remove elements. Thus they are PERFECT for unknown sizes. I'm sure there's a bunch of malloc, calloc, and realloc calls, but they are all done behind the scenes for you and you don't need to provide a size. If you used an array, you'd have to do that all yourself.

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.