Not logged in, Join Here! or Log In Below:  
 
News Articles Search    
 

 Home / General Programming / How to define a stl vector compatible comparision? Account Manager
 
Archive Notice: This thread is old and no longer active. It is here for reference purposes. This thread was created on an older version of the flipcode forums, before the site closed in 2005. Please keep that in mind as you view this thread, as many of the topics and opinions may be outdated.
 
Axel

April 28, 2005, 12:22 PM

For example:

  1. #include <iostream>
  2. #include <vector>
  3.  
  4. class foo
  5. {
  6. public:
  7.         foo(unsigned int value) : value(value) {}
  8.         bool operator==(const foo c) {
  9.                 return value == c.value;
  10.         }
  11.         bool operator!=(const foo c) {
  12.                 return value != c.value;
  13.         }
  14. private:
  15.         unsigned value;
  16. };
  17.  
  18. int main()
  19. {
  20.         std::vector<foo> bar,qux;
  21.  
  22.         bar.push_back(foo(2));
  23.         bar.push_back(foo(1));
  24.         qux.push_back(foo(2));
  25.         qux.push_back(foo(1));
  26.  
  27.         std::cout << (foo(2) == foo(2)) << std::endl; // works
  28.         std::cout << (bar == qux) << std::endl; // doesn't work
  29. }


Why doesn't this work?

 
Rud0lf

April 28, 2005, 12:55 PM

This is how you do it:

  1.  
  2.  
  3. #include <algorithm>
  4.  
  5. ...
  6.  
  7. std::equal( bar.begin(), bar.end(), qux.begin() );
  8.  
  9.  


You should make sure the ranges are of equal length first.

 
Axel

April 28, 2005, 12:56 PM

That's a workaround, but not an answer to my question. I can't believe this is not possible...

 
Rud0lf

April 28, 2005, 01:12 PM

It is possible, but you need to declare your foo equality operator const.

 
Jeroen

April 29, 2005, 06:45 AM

It should work. Dinkumware mentions "template bool operator==":

The template function overloads operator== to compare two objects of template class vector. The function returns left.size() == right.size() && equal(left. begin(), left. end(), right.begin()).

http://www.dinkumware.com/manuals/reader.aspx?b=p/&h=vector.html#operator==

It could be one of those things some implementations have but others do not.

 
This thread contains 5 messages.
 
 
Hosting by Solid Eight Studios, maker of PhotoTangler Collage Maker.