Back to Problem Solutions forum
OK I'm stuck on this one. How do I create an array of unknown size in C++? I know one solution is to use vectors but I have not learned how to do that yet. Can anyone start me off in the right direction? It will be much appreciated
quick guide to vectors:
#include <vecotor>
vector<T>name; //T is type like vector<int>numbers
name.push_back(element); //adds elements to the back of the vector
as for accesing vector elements its the same as using arrays
name[0]- first element and so on
Workaround without vectors:
If you want to solve this task without vector you can just set array size to some big number like 1000, and stop all input or calculations with it when you reach 0
The workaround worked - thanks! So, to populate a vector from an input stream I would just iterate on name.push_back(element)?
Yeah, and to iterate throught the vector you need to use size function qucik example for vector input and output:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int>numbers;
int n;
while(cin>>n)
numbers.push_back(n);
for(int i=0; i<name.size();i++)
cout<<name[i]<<" ";
}
Thanks for your help - I'll try that on the next suitable problem that comes up.