【问题标题】:An efficient data structure to hold structure variable with sorting capability一种有效的数据结构,用于保存具有排序能力的结构变量
【发布时间】:2011-04-14 12:51:36
【问题描述】:

我有一个结构

struct dbdetails
{
    int id;
    string val;
};

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

【问题讨论】:

  • try 是 C++ 中的保留关键字。你确定这个struct 叫做“try”吗?
  • 不,我只是想引用一个例子。我没有使用尝试。在我的程序中它被命名为 dbdetails。
  • 哦,好的。我已编辑问题以包含该名称,以免导致编译错误。

标签: c++ data-structures struct


【解决方案1】:

您需要一个自定义函子来比较您的尝试。这应该可以解决问题:

#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());
...

如果您有任何后续问题,请随时提出。你有 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());
...

【讨论】:

  • 另一种方法是将 less 运算符定义为结构的成员,并避免编写自定义比较器。
【解决方案2】:

您可以使用std::map。它们是按键排序的,所以你可以这样做:

std::map<int, std::string> myStuff;

这是一个以int 为键和std::string 为值的映射。当你遍历 map 时,你会发现它是自动按 key 排序的。

请注意,使用此解决方案您将不再需要您的 struct。如果您绝对需要 struct 中的数据(可能与某些外部库交互),您可以随时根据需要将数据从 map 复制到 struct 中。

【讨论】:

    【解决方案3】:

    您可以拥有struct 中的vector,然后将它们排序为:

    std::sort(vectStruct.begin(), vectStruct.end(), &vectStructSort);
    
    bool vectStructSort(Try const& lhs, Try const& rhs) { // try is keyword.
        return lhs.id < rhs.id;
    }
    

    【讨论】:

    • 我真的没有抓住保留尝试的使用。在我的帖子中对此进行了编辑。
    【解决方案4】:

    这取决于您对数据容器的要求。 您可能会发现一个有用的集合(在 Stl 中,Set 是一个排序关联容器,用于存储 Key 类型的对象)。甚至是散列集或排序数组。

    如果您知道需要对元素进行排序,最好使用排序容器,而不是每次需要时都对其进行排序。

    【讨论】:

    • 哈希集/映射是无序的,AFAIK。它们提供快速查找,但它们是无序的——并且无法排序。
    【解决方案5】:

    所有订购的容器(std::setstd::mapstd::multisetstd::multimap)都已订购。非有序容器(std::liststd::vectorstd::deque)可以通过提供比较函数和使用std::sort(向量、双端队列)或将该比较器提供给成员方法(列表)来排序。

    这一切都归结为您真正需要什么。如果您需要始终保持元素排序,那么排序容器可能比修改容器和重新排序更有效。另一方面,如果不需要始终对容器进行排序,但能够修改元素,那么您可能更喜欢向量。排序容器将键作为常量对象维护,因为修改键会破坏排序不变量。

    在某些情况下,需要始终对容器进行排序,但在某些初始化阶段之后它不会改变。在这种情况下,初始化后排序的未排序容器就可以了。

    【讨论】:

      【解决方案6】:

      您可以根据结构成员对向量进行排序。您只需要一个自定义比较器。

      【讨论】:

        猜你喜欢
        • 2022-06-10
        • 2012-08-06
        • 1970-01-01
        • 2016-11-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多