So for one small part of a project, I need to increase the size of an array by 5 spaces. When the code runs and the user enters whatever size and values they want for the array (I'm using 5 for the size and 1 2 3 4 5 as the values for this example), it should output 1, 2, 3, 4, 5, 0, 0, 0, 0, 0, but I can't quite get it work properly.
#include <iostream>
#include <vector>
int main()
{
std::cout << "Enter the array size: ";
int size;
std::cin >> size;
// create a sized vector, initial element values set to zero
std::vector<int> vec(size);
std::cout << "Enter the array values: ";
// a regular for loop can easily access outside a vector's boundaries
for (int i = 0; i < size; i++)
{
std::cin >> vec[i];
}
std::cout << '\n';
std::cout << "Your array: ";
// using iterators makes it harder to access elements outside a vector's boundaries
// if you are not modifying the elements use const iterators
for (std::vector<int>::const_iterator itr { vec.cbegin() }; itr != vec.cend(); itr++)
{
std::cout << *itr << ' ';
}
std::cout << "\n\n";
std::cout << "Increase size? (Y or N): ";
char choice;
std::cin >> choice;
std::cout << '\n';
if (choice == 'y' || choice == 'Y')
{
vec.resize(size + 5);
std::cout << "The array is now: ";
// a range based for loop
for (constauto& itr : vec)
{
std::cout << itr << ' ';
}
std::cout << "\n\n";
}
std::cout << "Goodbye!\n";
}
Enter the array size: 5
Enter the array values: 5 10 15 20 25
Your array: 5 10 15 20 25
Increase size? (Y or N): y
The array is now: 5 10 15 20 25 0 0 0 0 0
Goodbye!
The for loop iterator at line 26 could have been initialized using auto: for (auto itr { vec.cbegin() }; itr != vec.cend(); itr++)