views:

60

answers:

3

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<_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!

+4  A: 

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.

Alex Martelli
Yup. Wasn't sure about that. Thanks a lot!
Poni
@Poni, you're welcome!
Alex Martelli
+1  A: 

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

Billy ONeal
A: 

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