Task 16 Average of an Array - Cplusplus

Back to Problem Solutions forum

jpl_thefirst     2016-05-02 16:13:32

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

Photon     2016-05-02 17:18:18
User avatar

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

jpl_thefirst     2016-05-04 07:27:03

The workaround worked - thanks! So, to populate a vector from an input stream I would just iterate on name.push_back(element)?

Photon     2016-05-04 13:33:57
User avatar

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]<<" ";
}
jpl_thefirst     2016-05-04 14:34:42

Thanks for your help - I'll try that on the next suitable problem that comes up.

Please login and solve 5 problems to be able to post at forum