开发者

Random access and update of an stl::set

I'm using a stl::set to keep elements sorted as they are inserted. My question is about the random access. If I have a complex class(difficult to init, for example), I found that is easy to insert,开发者_如何转开发 because I define the less operator into class. But if the key is the class itself, how do I need to access to the class? With a find()? I need to init a complex class only to find my class?

So my question is: how to random access to a set elements when elements are complex classes difficult to initialize?

Thanks


you can:

1) create a special "lightweigt" initializer for your class to create "ligtweight" version of your object and use such "lightweight" objects only as keys to access the map

2) use a map instead of a set.

I'd prefer the second solution.


I don't think it is possible : as you already noticed, the std::set<>::find member function expects a const key_type & (which, in a std::set is identical to value_type).

If you object is expensive to construct, chances are that you should better use a std::map (which also is a sorted container), possibly with values being (smart) pointers on your type.


Set doesn't support random access iterator. If you want other way to compare objects(won't use operator <) you must do following

1)first way

bool compareFunciton(const setElementClass& lhs,const setElementClass& rhs)
{
    //return true if lhs's key is smaller than rhs and false at other case
}


set<setElementClass,compareFunction>  someSet;

2)Or you can use function-class instead of function like this

class compareClass
{
public:
    bool opreator()const setElementClass& lhs,const setElementClass& rhs)
   {
          //return true if lhs's key is smaller than rhs and false at other case
    }
};

compaerClass comp;
set<setElementClass,comp>  someSet;

Also I think you must look at functional header. There you can find some function-classes which you can use in the feauture. http://www.cplusplus.com/reference/std/functional/


Do you have to use a set?

You might be better off using a map and generating a key (maybe a numerical index or a string) for your complex class, and then using the objects of the complex class as a value.

Just make sure your key follows the same ordering rules as the value. std::map is implemented as a tree, so it will also keep the items sorted according to the keys.


You only need to define a less struct like this:

#include <set>

using std::binary_function;
using std::set;


struct very_complex
{
    int x, y;
};

struct less : public binary_function<very_complex, very_complex, bool>
{
    bool operator() (very_complex const& lho, very_complex const& rho)
    {
        if (lho.x != rho.x)
            return lho.x < rho.x;
        return lho.y < rho.y;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜