一种有效的数据结构,用于保存具有排序功能的结构变

set*_*thu 5 c++ struct data-structures

我有一个结构

struct dbdetails
{
    int id;
    string val;
};
Run Code Online (Sandbox Code Playgroud)

我需要一个C++中的数据结构,它可以保存具有排序功能的结构变量.可能吗?我在看vector,它可以保存结构变量,但是我无法根据id对它进行排序,因为它是一个结构成员.有什么建议?

Gab*_*ber 6

您需要一个自定义仿函数来比较您的尝试.这应该做的伎俩:

#include <algorithm>
#include <vector>
// try is a keyword. renamed
struct sorthelper : public std::binary_function<try_, try_, bool>
{
    inline bool operator()(const try_& left, const try_& right)
    {   return left.id < right.id;  }
};

...
std::vector<try_> v;
// fill vector 
std::sort(v.begin(), v.end(), sorthelper());
...
Run Code Online (Sandbox Code Playgroud)

如果您有任何后续问题,请随时询问.你有Stroustrup书吗?

编辑:Matteo的建议:

struct try_
{
    int id;
    string val;
    bool operator<(const try_& other) const
        {return id < other.id;}

}; // no s here plz.

...
std::vector<try_> v;
// fill vector 
std::sort(v.begin(), v.end());
...
Run Code Online (Sandbox Code Playgroud)

  • 另一种方法是将较少的运算符定义为结构的成员,并避免编写自定义比较器. (2认同)