简体   繁体   中英

How to write a class in c++ with proper iterators so it can be used by standard library containers and algorithms

Suppose I wrote a class in c++ like this:

class data
{
private:
    int a,b,c,d;
public:
    data(){
        a=b=c=d=0;
    }
    data(int aa,int bb, int cc, int dd)
    {
        a=aa,b=bb,c=cc,d=dd;
    }
    int get_b(){return b;}
    int get_a(){return a;}
};

Now I know want to learn how to write operators and iterators for this class so that it can be used with standard library containers

Like: set<string> x; this is possible. I want to use this data class as set<data> x; and want to use iterators like set<data>::iterator it;

I have tried to google out the procedure, but nowhere could find an example implementation which would actually explain the procedure.

If you want to use it in a std::set , std::map , std::unordered_map , std::unordered_set you need to implement a "weak less than operator"

bool operator<(const data& other_data) {
   return ....;
}

For other containers like std::vector , std::deque , std::list data is ok as it is.

Like: set x; this is possible. I want to use this data class as set x; and want to use iterators like set::iterator it;

I believe you want to use you class as data to fit into standard containers (vector/set etc).

For Sequence Containers (Vector)

int main()
{
    data d1(1, 2);
    data d2(3, 4);

    vector<data> vec{d1, d2};  //initialize your container with your "data" type objects.
    for(auto iter = vec.begin(), iter != vec.end();iter++)
        cout<<*iter;     //for this you need to implement "operator<<" in your data class.    
    return 0;
}

For Associative Containers (Set)

int main()
{
    data d1(1, 2);
    data d2(3, 4);
    //you need to impelment "< or >" relational operator in you data class.
    set<data> st{d1, d2};  //initialize your container with your "data" type objects.
    for(auto iter = vec.begin(), iter != vec.end();iter++)
        cout<<*iter;     //for this you need to implement "operator<<" in your data class.    
    return 0;
}

Add this in your class definition.

friend ostream& operator<<(ostream& os, const base& obj)
{
    return (os<<obj.memVariable);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM