【问题标题】:std::sort and std::unique problem with a struct结构的 std::sort 和 std::unique 问题
【发布时间】:2010-09-04 02:36:34
【问题描述】:

以下代码:

#include <vector>
#include <algorithm>

struct myStructDim
{
    int     nId;
    int     dwHeight;
    int     dwWidth;
};    

void main()
{
    ::std::vector<myStructDim>  m_vec_dim;

    ::std::sort(m_vec_dim.begin(), m_vec_dim.end());
    m_vec_dim.erase(
        ::std::unique(m_vec_dim.begin(), m_vec_dim.end()),
        m_vec_dim.end()
        );
}

不会编译有很多错误,例如:

错误 C2784: 'bool std::operator ==(const std::vector<_ty> &,const std::vector<_ty> &)' : 无法推断出模板参数 'const std::vector<_ty> &' 来自 'myStructDim'

我知道我必须重写一两个运算符。

请问具体是哪几个?

感谢支持!

【问题讨论】:

    标签: c++ stl operators compilation std


    【解决方案1】:

    您需要比较运算符来表达“小于”和“相等”的关系。定义独立的布尔函数 operator&lt;operator==,它们接受两个参数,每个参数 const myStructDim&amp;,并完全按照您需要的方式执行比较,这可能比将 then 定义为 struct 中的方法更简单。

    【讨论】:

    • 是的。不确定。非常感谢!
    【解决方案2】:

    sort 需要某种形式的比较函数,unique 需要某种形式的相等函数。

    【讨论】:

      【解决方案3】:

      像其他人提到的 operator

      我在这个例子中使用了 C++0x lambdas,但没有它也可以实现。

         std::sort(
            vec_dim.begin(), 
            vec_dim.end(), 
            [] (myStructDim const & l, myStructDim const & r) {return l.nId < r.nId;}
            ); 
      
         vec_dim.erase( 
            std::unique(
               vec_dim.begin(), 
               vec_dim.end(),
               [] (myStructDim const & l, myStructDim const & r) {return l.nId == r.nId;}
               ), 
            vec_dim.end() 
            ); 
      

      【讨论】:

        【解决方案4】:

        没有operato就不可能有某种独特的> ?我的意思是我可以理解,对于 unique 我需要一个 operator== (就像苹果不是椅子)但是为什么椅子应该比苹果大???我将不得不为一些没有意义的对象实现一个运算符!也许某种聚类会更有意义。 所以我决定实施我自己的问题,在我看来这是一个更有意义的解决方案:

        模板内联 void uniques(listtype In,listtype& Out) { Out.resize(In.size()); std::copy(In.begin(),In.end(),Out.begin()); listtype::iterator it = Out.begin(); listtype::iterator it2= Out.begin(); 它2++; int tmpsize = Out.size();

            while(it!=Out.end())
            {
            it2 = it;
            it2++;
            while((it2)!=Out.end())
                {
                if ((*it)==(*it2))
                    Out.erase(it2++);
                else
                    ++it2;
                }
            it++;
        
            }
        }
        

        也许不是最好的解决方案,但目前我不知道更好

        【讨论】:

          猜你喜欢
          • 2010-09-20
          • 2020-11-03
          • 2016-03-06
          • 2016-08-10
          • 1970-01-01
          • 1970-01-01
          • 2011-05-15
          • 2013-01-27
          • 2018-05-16
          相关资源
          最近更新 更多