/*
* @topic T0M260 C++ crash course samples 2016
* @brief Demonstrates std::vector
*/
#include <iostream>
#include <cstdlib>
#include <vector>
#include <string>
// Function prototypes
void display( char* pmessage );
void display( int* pvalue );
void display( int value );
void display( std::vector< int >* pvect );
int main()
{
const std::string prompt = "How many integers would you like? ";
std::cout << ( prompt + "\n" );
int array_size;
std::cin >> array_size;
// A vector is a dynamic array that eliminates the need
// for "new" and "delete" low-level memory management
// int iarray[ array_size ]; // this is not allowed
// int* iarray = new int[ array_size ]; // dynamic memory allocation
// ...use iarray...
// delete[] iarray; // each new requires delete!
// A vector eliminates new/delete mess: it does it internally
std::vector< int > iarray( array_size );
// The vector::data() member function
// returns address of the memory block allocated by the
// vector to store the data. This is necessary when passing
// vector elements to functions which expect a C array as
// the input:
iarray.data(); // same as &iarray[ 0 ]
iarray[0] = 12345; // vector allows using index to access its elements
iarray[1] = 11111;
iarray[2] = 22222;
display( &iarray[0] );
display( &iarray );
system("pause");
return 0;
}
// Overloaded display() functions
void display( std::vector<int>* pvect )
{
// print content os the vector
for ( size_t idx = 0; idx < pvect->size(); ++idx ) {
std::cout << ( *pvect )[ idx ] << " ";
}
std::cout << "\n";
}
void display(char* pmessage)
{
std::cout << pmessage;
}
void display(int* pvalue)
{
std::cout << *pvalue << "\n";
}
void display(int value)
{
std::cout << value << "\n";
}