如何用自定义比较表示一组指针,但保持原始指针重复比较 [英] How to Represent a Set of Pointers with Customized Compare but Maintaining the Original Raw Pointer Duplicate Comparison

查看:133
本文介绍了如何用自定义比较表示一组指针,但保持原始指针重复比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我想保存一组指针,应该按照自定义的比较函数排序,但是唯一性应该仍然由指针本身确定。

Basically, I want to save a set of pointers, which should be sorted by my customized compare function, but the uniqueness should still be determined by the pointer itself.

但是:

#include <iostream>
#include <string>
#include <set>
#include <utility>
#include <functional>
using namespace std;

//         count, word
typedef pair<int, string> WordFreq;

struct WordFreqPointerCmp
{
    bool operator()(const WordFreq* lhs, const WordFreq* rhs) const
    {
        return lhs->first > rhs->first;
    }
};

int main()
{
    set<WordFreq*, WordFreqPointerCmp> s;
    s.insert(new WordFreq(1, "word1")); // Inserted
    s.insert(new WordFreq(1, "word2")); // This is not inserted
    s.insert(new WordFreq(3, "word3")); // Inserted

    cout << s.size() << endl;

    for (set<WordFreq*, WordFreqPointerCmp>::iterator it = s.begin();
         it != s.end(); ++it)
    {
        cout << (*it)->second << ": " << (*it)->first << endl;
    }

    return 0;
}
/* Output:
2
word3: 3
word1: 1
 */

正如你可以看到,排序是正确的,但重复测试是错误的。我想要做的是:

As you can see that the ordering is correct, but the duplicate testing is wrong. What I am trying to do is:


  • 对于排序,我想使用 WordFreqPointerCmp ;

  • 对于重复测试,我想使用raw Pointer比较的原始含义,即地址比较,这意味着,即使下面的集合应该有两个条目

  • For ordering, I want to use WordFreqPointerCmp;
  • For duplicate testing, I want to use the original meaning of raw Pointer comparsion, i.e., the address comparison, which means, even the following set should have two entries in the set;

set<WordFreq*, WordFreqPointerCmp> s;
s.insert(new WordFreq(1, "word1"));
s.insert(new WordFreq(1, "word1"));


template<>
struct greater<WordFreq*>
{
    bool operator()(WordFreq* const& lhs, WordFreq* const& rhs) const
    {
        return lhs->first > rhs->first;
    }
};
set<WordFreq*, greater<WordFreq*> > s;


推荐答案

同样的问题,所以它可以帮助某人..

while this post is ancient, I've just faced the same issue, so it may help somebody..

在你的代码中,你只处理一个值,但如果值相同呢?然后设置它作为相同的元素。正确的解决方案是扩展你的比较功能,给出设置额外的信息如何测试重复。它可以是任意比较字符串,例如在你的情况下:

In your code you only handle one value, but what if values are the same? Then set treats it as the same element. The proper solution would be to extend your compare function to give set additional information how to test for duplicates. It can be something arbitrary like comparing strings, for example in your case:

struct WordFreqPointerCmp
{
    bool operator()(const WordFreq* lhs, const WordFreq* rhs) const
    {
        if (lhs->first == rhs->first)
            return lhs->second > rhs->second;
        else
            return lhs->first > rhs->first;
    }
};

这篇关于如何用自定义比较表示一组指针,但保持原始指针重复比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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