// @topic T061020 std::vector demo
// @brief auto, std::sort( ), std::find( ), std::vector< >::iterator

#include <cstdlib>
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

int do_stuff()
{
    // Using C array
    std::cout << "Array\n";
    int myarray[] = { 10000, 2000, 300, 40, 5 };
    std::sort( myarray, myarray+5 );    // arrays can be sorted
    int* pbegin = myarray;              // upper boundary
    int* pend = myarray + 5;            // lower boundary
    for ( ; pbegin < pend; ++pbegin ) {
        std::cout << *pbegin << " ";
    }

    // Using std::vector
    std::cout << "\nVector\n";
    std::vector< int > vect = { 10000, 2000, 300, 40, 5 };

    //std::sort(vect.begin(), vect.end());
    auto it = std::find( vect.begin(), vect.end(), 40 );
    if ( it != vect.end() ) {
        std::cout << "\nfound element" << *it << "\n";
        std::cout
            << "\nthe value is "
            << std::distance(vect.begin(), it)
            << " elements away from the beginning\n";
        *it = 50; // iterator behaves like pointer
        ++it;
    } else {
        std::cout << "\nelement not found\n";
        std::cout
            << "\nthe value is "
            << std::distance(vect.begin(), it)
            << " elements away from the beginning\n";
    }

    // Before C++2011 we had to provide the type ourselves:
    //std::vector< int >::iterator vbegin = vect.begin();
    //std::vector< int >::iterator vend = vect.begin() + 5;

    // After C++2011 we can ask compiler to deduce the type from the initializer:
    auto vbegin = vect.begin();
    auto vend = vect.end();

    // Range loop can be used to access a sequence of elements
    for ( auto& value : vect ) {
        std::cout << value << " ";
        value = 0;
    }
    std::cout << "\n";

    // Alternatively, this loop is using the iterators to access the elements
    for ( ; vbegin < vend; ++vbegin ) {
        std::cout << *vbegin << " ";
    }
    std::cout << "\n";

    // Vectors are dynamic arrays - the size can grow and collapse:
    vect.push_back( 100 );
    vect.clear();
    return 0;
}

int main()
{
    int result = do_stuff();
    system( "pause" );
    return result;
}