开发者

std::sort and std::unique problem with a struct

The following code:

#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()
        );
}

will not compile with many errors, such as:

error C2784: 'bool std::operator ==(const std::vector<_开发者_StackOverflow社区Ty,_Alloc> &,const std::vector<_Ty,_Alloc> &)' : could not deduce template argument for 'const std::vector<_Ty,_Alloc> &' from 'myStructDim'

I understand that I have to override an operator or two.

Which ones and how exactly please?

Thanks for the support!


You need comparison operators to express the "less-than" and "equality" relationships. Defining stand-alone boolean functions operator< and operator== that take two arguments, each const myStructDim&, and perform the comparison exactly the way you require, is probably simpler than defining then as methods within the struct.


Like others mentioned operator< and operator== would do the trick but I usually prefer to pass a comparision predicate.

I use C++0x lambdas in this example but it can be implemented without that.

   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() 
      ); 


You need some form of comparison function for sort, and you need some form of equality function for unique.


Is it not possible to have some kind of unique without having the operato> ? I mean I can understand that for unique I need an operator== (like apples are not chairs) but why should a chair be greater than an apple ??? I would have to implement an operator for some objects where it makes no sense ! maybe some kind of clusering would make more sense. So I decided to implement what the question is for my self here is in my opinion a solution that makes more sense:

template inline 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(); it2++; int tmpsize = Out.size();

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

    }
}

maybe not the best solution but at the moment I don t know betters

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜