Array to Vector

Hi

I made this program that randomly generates an array and then displays the array in reverse order.
I would like to know how would you program this exact program using vectors?

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
srand(time(0));

int arr[10] = {0};

cout << "Forward Array:" << endl;

for (int i=0; i<10; i++)
{
arr[i] = 1+(rand()%10);
}

for(int i=0; i<10; i++)
{
cout << arr[i] << endl;
}
cout << endl;
cout << "Reverse Array:" << endl;

int i,j,temp;

for (i=0, j=10-1; i<10/2; i++, j--)
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}

for (int i=0; i<10; i++)
{
cout << arr[i] << endl;
}

return 0;
}


declaring :
1
2
3
4
5
6
int arr[10] = {0}; // normal array

vector<int> arr; // empty vector
arr.reserve( SOME_VALUE ); // this is optional, but reduces overhead of push_back()

vector<int> arr(10); // vector w/ 10 elements 


adding elements :
1
2
3
4
5
6
7
arr[ i ] = N; // normal array

arr.push_back( N ); // vector

// if u declare the vector as vector<int> arr(10) u will only need
// to use operator[] just like a normal array
cin >> arr[ i ];


querying the size :
1
2
3
for( int i = 0; i < N; ++i ) ; // array

for( size_t i = 0; i < arr.size(); ++i ) ; // vector 


remember to #include <vector>
see : http://www.cplusplus.com/reference/vector/vector/
for other methods of std::vector<>

EDIT
To reverse an array or vector or any other container, you can simply use :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <vector>
#include <algorithm>

int main()
{
    int arr[ 10 ] = { ... };
    vector<int> vec = { ... }; // will also work for vector

    // reverse an array
    std::reverse( std::begin(arr), std::end(arr) ); 
    
    // reverse a vector (u can also use std::begin(vec) and std::end(vec)
    std::reverse( vec.begin(), vec.end() );
}
Last edited on
You only need to change line int arr[10] = {0}; to std::vector<int> arr(10);.
Last edited on
Thanks
Topic archived. No new replies allowed.