如何在C ++中具有一组结构

编程入门 行业动态 更新时间:2024-10-14 20:22:54
本文介绍了如何在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 ++中具有一组结构

本文发布于:2023-05-23 15:05:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1326428.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:结构   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!