I need help using the push_back operation. See code.
Code:
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
#include <vector>
using namespace std;
double FillVec (vector <int> &);
void PrintVec (vector <int>);
double Average (vector <int>);
int FindLargest (vector <int>);
void Exchange (vector <int> &, int);
int main (void)
{
vector <int> Vec1 (100);
vector <char> CharVec [26];
float Ary1 [10];
int IndexOfLargest, TheNum = 0;
srand (time(NULL));
FillVec(Vec1);
cout << "The average is " << setiosflags(ios::fixed) << setprecision(2) <<
Average (Vec1) << endl << endl;
PrintVec (Vec1);
FindLargest (Vec1);
cout << "The largest element is " << setiosflags(ios::fixed) << setprecision(2) <<
FindLargest(Vec1) << endl << endl;
Exchange (Vec1, IndexOfLargest);
PrintVec(Vec1);
return 0;
}
double FillVec (vector <int> & ivec)
{
int Total = 0;
int Size;
vector <int> MyVec (100);
if (ivec.size() != 0)
{
MyVec = ivec;
Size = ivec.size();
}
else
Size = 100;
for (int i = 0; i < Size; i++)
{
MyVec[i] = rand() % 199 - 99;
Total += MyVec[i];
}
ivec = MyVec;
return (double(Total) / ivec.size());
}
void PrintVec (vector <int> ivec)
{
for (int index = 0; index < ivec.size(); index++)
{
cout << setw(5) << ivec[index];
if (index % 10 == 9)
cout << endl;
}
cout << endl;
}
double Average (vector <int> ivec)
{
int sum = 0;
int Size = ivec.size();
for (int index = 0; index < Size; index++)
sum += ivec [index];
return (double (sum) / Size);
}
int FindLargest (vector <int> ivec)
{
int maxIndex = 0;
for (int index = 1; index < 100; index++)
if(ivec[maxIndex] < ivec[index])
maxIndex = index;
return ivec[maxIndex];
}
void Exchange (vector <int> & ivec, int i)
{
ivec.push_back(100);
for (i = 0; i < 100; i++)
ivec[i];
}
After finding the largest element of Vec1 and printing it out. Exchange is supposed to exchange the largest element of Vec1 with the last element of the vector. Am I using push_back correctly? I read through the section in my book about push_back, but I'm still unsure. My output just puts the number 100 at the end of the vector.
Thank You,
Kristina