unique



#include <algorithm>
#include <iostream>
#include <vector>
                                                                                                                
using std::vector,
    std::unique,
    std::cerr;
                                        
class Temp{
    public:
        int a, b;
        Temp(int i, int j):a(i), b(j){}
};

bool operator==(const Temp& l, const Temp& r)
{
    return l.a == r.a && l.b == r.b;
} 
                        
typedef vector<Temp> my_vector;
            
int main(){
    my_vector a = {Temp(5, 25), Temp(6, 36), Temp(6, 36), Temp(7, 49), Temp(8, 64), Temp(9, 81), Temp(12, 144)};

    auto print = [] (Temp t){
        cerr << "Temp(" << t.a << ", " << t.b << ")\n";
    }; 

    //this is a 2 step process.
    my_vector::iterator i = unique(a.begin(), a.end());
    a.erase(i, a.end());

    cerr << "a after unique:\n";
    for_each(a.begin(), a.end(), print);

    auto test = [](Temp t, Temp u)->bool{
        if(t.a == u.a && t.b == u.b){
            return true;
        }
        return false;
    };

    a.insert(a.begin(), Temp(5, 25));
    cerr << "a after insert:\n";
    for_each(a.begin(), a.end(), print);

    i = unique(a.begin(), a.end(), test);
    a.erase(i, a.end());

    cerr << "a after unique:\n";
    for_each(a.begin(), a.end(), print);

    return 0;
}      
C++ Examples© 2024 TBD