如何在c++中拥有一组结构体

How to have a set of structs in C++

本文关键字:一组 结构体 拥有 c++      更新时间:2023-10-16

我有一个结构体,它有一个唯一的键。我想把这些结构体的实例插入到集合中。我知道要做到这一点Operator必须重载,这样set才能进行比较,以便进行插入操作。

#include <iostream>
#include <set>
using namespace std;
struct foo 
{
      int key;
};
bool operator<(const foo& lhs, const foo& rhs)
{
      return lhs.key < rhs.key;
}
set<foo> bar;
int main()
{
    foo *test = new foo;
    test->key = 0;
    bar.insert(test);
}

这可能有帮助:

struct foo
{
  int key;
};
inline bool operator<(const foo& lhs, const foo& rhs)
{
  return lhs.key < rhs.key;
}

如果使用名称空间,最好在相同的名称空间中声明operator<()函数。


为了编辑后的完整性,正如其他人指出的那样,您试图在需要foo的地方添加foo*

如果你真的想处理指针,你可以把foo*包装成一个智能指针类(auto_ptr, shared_ptr,…)。

但是请注意,在这两种情况下,您都失去了重载operator<的好处,它操作的是foo,而不是foo*

struct Blah
{
    int x;
};
bool operator<(const Blah &a, const Blah &b)
{
    return a.x < b.x;
}
...
std::set<Blah> my_set;
然而,我不喜欢重载operator<,除非它有直观的意义(说一个Blah"小于"另一个Blah真的有意义吗?)。如果没有,我通常提供一个自定义比较器函数:
bool compareBlahs(const Blah &a, const Blah &b)
{
    return a.x < b.x;
}
...
std::set<Blah,compareBlahs> my_set;

可以在类中重载operator <

struct foo 
{
  int key;
  bool operator < (const foo &other) const { return key < other.key; }
};

在你的问题中,如果你想使用set<foo> bar;作为声明,那么你应该插入value as,

bar.insert(*test);

但这不是一个好主意,因为你正在制作冗余的副本。

看ereOn的答案,它是正确的。

你代码中的真正问题是:

foo *test = new foo;
test->key = 0;
bar.insert(test);

在集合中插入一个指针,而不是struct。将insert更改为:

 bar.insert( *test );
 //          ^

编辑:但你需要delete foo,因为它将被复制到set。或者直接在堆栈上创建它(使用set和指针不是一个好主意,因为排列将是"奇怪的"- set将根据指针的地址排序)

最好是给foo一个构造函数:

struct foo
{
    foo(int k) : key(k) { }
    int key;
};

然后添加,而不是…

foo *test = new foo;
test->key = 0;
bar.insert(test);   // BROKEN - need to dereference ala *test
// WARNING: need to delete foo sometime...

…您可以简单地使用:

bar.insert(foo(0));

问题不在你的集合;它在你的test对象。这里使用的是Java风格。在c++中,我们只需要写:

set<foo> bar;
int main()
{
    foo test; // Local variable, goes out of scope at }
    test.key = 0;
    bar.insert(test); // Insert _a copy of test_ in bar.
}

在c++11中我们可以使用lambda表达式,我使用这种方式,类似于@Oliver给出的方式。

#include <set>
#include <iostream>
#include <algorithm>
struct Blah
{
    int x;
};

int main(){
    auto cmp_blah = [](Blah lhs, Blah rhs) { return lhs.x < rhs.x;};
    std::set<Blah, decltype(cmp_blah)> my_set(cmp_blah);
    Blah b1 = {2};
    Blah b2 = {2};
    Blah b3 = {3};
    my_set.insert(b1);
    my_set.insert(b2);
    my_set.insert(b3);
    for(auto const& bi : my_set){
        std::cout<< bi.x << std::endl;
    }
}
演示