如何在C ++中具有一组结构 [英] How to have a set of structs in C++

查看:48
本文介绍了如何在C ++中具有一组结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有唯一键的结构.我想将这些结构的实例插入到集合中.我知道要做到这一点<操作符必须重载,以便set可以进行比较才能进行插入.

I have a struct which has a unique key. I want to insert instances of these structs into a set. I know that to do this the < operator has to be overloaded so that set can make a comparison in order to do the insertion.

以下内容无效:

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

If you are using namespaces, it is a good practice to declare the operator<() function in the same namespace.

出于编辑后的完整性考虑,并且正如其他人指出的那样,您正在尝试添加 foo * 到期望 foo 的地方.

For the sake of completeness after your edit, and as other have pointed out, you are trying to add a foo* where a foo is expected.

如果您真的想处理指针,则可以将 foo * 包装到一个智能指针类中( auto_ptr shared_ptr 、...).

If you really want to deal with pointers, you may wrap the foo* into a smart pointer class (auto_ptr, shared_ptr, ...).

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

But note that in both case, you loose the benefit of the overloaded operator< which operates on foo, not on foo*.

这篇关于如何在C ++中具有一组结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆