泛型算法 与 操作符重载

  试想将若干无序的数据进行排序,这些数据可以是int、string、double类型,但采用的排序算法无关类型。当编写的C++代码的类型无关的算法或数据结构时,我们更愿意只写一次,而不是为不同的类型都重写一次。

  在《数据结构与算法分析C++描述》一书中给出了类模板的例程:

#include <iostream>

using namespace std;

template <typename Object>
class MemoryCell
{
    public :
        explicit MemoryCell( const Object &initialValue = Object() )
            : storedValue( initialValue ) {}
        const Object & read() const
        { return storedValue; }
        void write( const Object &x )
        { storedValue = x; }
    private :
        Object storedValue;
};

int main()
{
    MemoryCell<int> m1;
    MemoryCell<string> m2( "hello" );
    m1.write( 37 );
    m2.write( m2.read() + " world" );
    cout << m1.read() << endl << m2.read() << endl;

    return 0;
}

还有使用函数模板对类类型进行操作,其中重载了比较运算符<、和<operator<<并增加了一个输出自身数据的成员函数print:

#include <iostream>
#include <vector>

using namespace std;

template <typename Comparable>                        //函数模板,返回容器中最大的元素。
const Comparable &findMax( const vector<Comparable> &a )
{
    int maxIndex = 0;

    for ( int i = 1 ; i < a.size() ; i++ )
        if ( a[maxIndex] < a[i] )
            maxIndex = i;

    return a[maxIndex];
}

class Employee
{
    public :
        void setValue( const string &n,double s )
        { name = n; salary = s; }

        const string &getName() const
        { return name; }
        void print( ostream &out ) const                //打印值
        { out << name << "(" << salary << ")"; }
        bool operator< ( const Employee &rhs ) const
        { return salary < rhs.salary; }

    private :
        string name;
        double salary;
};

ostream &operator<< ( ostream &out,const Employee &rhs )//重载<<操作符
{
    rhs.print( out );
    return out;
}

int main( void )
{
    vector<Employee> v( 3 );

    v[0].setValue( "George Bush",400000.00 );
    v[1].setValue( "Bill Gates",2000000000.00 );
    v[2].setValue( "Dr.Phil",13000000.00 );

    cout << findMax( v ) << endl;

    return 0;
}
我们一路奋战,不是为了改变世界,而是不让世界改变我们 ——《熔炉》
原文地址:https://www.cnblogs.com/ZRBYYXDM/p/5110872.html