C++ Problem resolution - is it the best way to simulate a "tuple"?

Posted by fbin on Stack Overflow See other posts from Stack Overflow or by fbin
Published on 2011-03-01T23:18:39Z Indexed on 2011/03/01 23:24 UTC
Read the original article Hit count: 122

Filed under:
|
|

Hi everyone! I've got the following problem:

"Write a template function vectorMAXMIN() that will accept a vector and a number indicating the size of the vector and will return the max and the min values of the vector"...

So i think in it... Create a class vector to avoid the "size" passing value and control the insertions and can get from this the max and min values... ( dunno if it's a good idea )

The problem is "how to return a tuple?" When i read the problem, i thought in a tuple to return "max, min values" is it correct?

The code:

#include <iostream>

template < typename T >
class _tuple
{
    public:
        T _Max;
        T _Min;
};

template < typename T >
class _vector
{
    public:
        _vector( int cnt = 0);
        ~_vector();
        _tuple< T > get_tuple( void );
        void insert( const T );
    private:
        T *ptr;
        int cnt;
        int MAX;
};

template < typename T >
_vector< T >::_vector( int N )
{
    ptr = new T [N] ; 
    MAX = N;
    cnt = 0;
}

template < typename T >
_tuple<T> _vector< T >::get_tuple( void )
{
    _tuple< T > _mytuple;
    _mytuple._Max = ptr[0];
    _mytuple._Min = ptr[0];
    for( int i = 1; i < cnt; i++)
    {
        if( _mytuple._Max > ptr[i]  )
            _mytuple._Max = ptr[i];
        if( _mytuple._Min < ptr[i] )
            _mytuple._Min = ptr[i];
    }
    return _mytuple;
}   

template < typename T >
void _vector< T >::insert( const T element)
{
    if( cnt == MAX )
        std::cerr << "Error: Out of range!" << std::endl;
    else
    {
        ptr[cnt] = element;
        cnt++;
    }
}

template < typename T >
_vector< T >::~_vector()
{
    delete [] ptr;
}

int main()
{
    _vector< int > v;
    _tuple < int > t;
    v.insert(2);
    v.insert(1);
    v.insert(5);
    v.insert(0);
    v.insert(4);
    t = v.get_tuple();
    std::cout << "MAX:" << t._Max;
    std::cout << " MIN:" << t._Min;
    return 0;
}

© Stack Overflow or respective owner

Related posts about c++

Related posts about homework