如何在c++中拥有一组结构体
How to have a set of structs in C++
我有一个结构体,它有一个唯一的键。我想把这些结构体的实例插入到集合中。我知道要做到这一点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;
}
}
演示相关文章:
- 在 c++ 中拥有一组结构的正确方法是什么?
- 使用一组结构,避免在一组结构中出现重复的结构
- 如何使用结构体的向量数组?
- 如何在构造函数中初始化结构体的动态数组?
- 动态分配一维结构数组:两种方法
- 如何创建一组std::结构
- 一组结构缺少元素
- 在高性能计算中更好的做法是:将数据结构传递到一个函数或一组变量中
- 一组具有不同 == 和 < 运算符语义的结构
- 对一组数字进行排序的最快数据结构(和排序算法)是什么
- 将一个结构与一组模式相匹配
- 使用std::copy将一个结构体的数组转换为另一个结构的Vector
- 按结构体的特定成员对结构体数组进行排序
- 制作一组结构
- 如何调用一个函数,它在一个单独的类中打印出一个结构体数组
- 发送/接收结构体而不是字符数组
- 如何创建一个结构体数组
- c++动态数组结构体分割错误
- c++中两组结构体的并集
- 如何在c++中拥有一组结构体