how do i populate a vector with a for loop
using only these declartions and 1 for loop
1 2 3 4 5 6 7 8 9 10 11 12
|
#include <iostream>
#include <vector>
using namespace std;
int main() {
const int NUM_GUESSES = 3;
vector<int> userGuesses(NUM_GUESSES);
return 0;
}
|
What would you like to populate the vector with? User guesses I guess? Just adding on to our code you can do this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
#include <iostream>
#include <vector>
using namespace std;
int main() {
const int NUM_GUESSES = 3;
vector<int> userGuesses(NUM_GUESSES);
for (int count = 0; count < NUM_GUESSES; count++)
{
cout << "Guess " << count+1 <<" Guuess a number" << endl;
cin >> userGuesses[count];
}
for (int count = 0; count < userGuesses.size(); count++)
{
cout << "Guess " << count+1 << " was: " << userGuesses[count] << endl;
}
return 0;
}
|
Personally, I would use this instead but both work.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
#include <iostream>
#include <vector>
using namespace std;
int main() {
const int NUM_GUESSES = 3;
int guess;
vector<int> userGuesses;
for (int count = 0; count < NUM_GUESSES; count++)
{
cout << "Guess " << count+1 <<" Guuess a number" << endl;
cin >> guess;
userGuesses.push_back(guess);
}
for (int count = 0; count < userGuesses.size(); count++)
{
cout << "Guess " << count+1 << " was: " << userGuesses[count] << endl;
}
return 0;
}
|
Last edited on
Topic archived. No new replies allowed.