gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:00:46 24 4
gpt4 key购买 nike

我有一个结构

struct dbdetails
{
int id;
string val;
};

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

最佳答案

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

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

关于c++ - 一种有效的数据结构,用于保存具有排序功能的结构变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3749233/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com