fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <cstring>
  4. #include <algorithm>
  5.  
  6. using namespace std;
  7.  
  8. class LoopDetectorData
  9. {
  10. char detectorName[20];
  11. public:
  12. LoopDetectorData( const char *str1)
  13. { strcpy(detectorName, str1); }
  14. friend bool operator== (const LoopDetectorData &v1, const LoopDetectorData &v2);
  15. };
  16.  
  17. bool operator== (const LoopDetectorData &v1, const LoopDetectorData &v2) {
  18. return strncmp(v1.detectorName,v2.detectorName, 20)==0;
  19. }
  20.  
  21. int main() {
  22. std::vector<LoopDetectorData *> Vec_loopDetectors;
  23. Vec_loopDetectors.push_back(new LoopDetectorData("abc"));
  24. LoopDetectorData *pld=new LoopDetectorData("def");
  25. Vec_loopDetectors.push_back(pld);
  26. Vec_loopDetectors.push_back(new LoopDetectorData("klm"));
  27.  
  28. const LoopDetectorData *searchFor = new LoopDetectorData( "def" ); // different pointer same value
  29. std::vector<LoopDetectorData *>::iterator counter = std::find(Vec_loopDetectors.begin(), Vec_loopDetectors.end(), searchFor);
  30. if (counter == Vec_loopDetectors.end())
  31. cout << "Compares pointers value of pointers, not values pointed to. Won't work"<<endl;
  32. else cout <<"Found pointer"<<endl;
  33.  
  34. auto counter2 = std::find(Vec_loopDetectors.begin(), Vec_loopDetectors.end(), pld);
  35. if (counter2 == Vec_loopDetectors.end())
  36. cout << "Not found ?? "<<endl;
  37. else cout <<"Found pointer, because this is one that was inserted in vector"<<endl;
  38.  
  39. auto counter3 = std::find_if(Vec_loopDetectors.begin(), Vec_loopDetectors.end(), [&searchFor](const LoopDetectorData *f)->bool { return *f == *searchFor; }
  40. );
  41. if (counter3 == Vec_loopDetectors.end())
  42. cout << "Not found ??? "<<endl;
  43. else cout <<"Found because ad-hoc lambda function compares by value"<<endl;
  44.  
  45.  
  46. return 0;
  47. }
Success #stdin #stdout 0s 3276KB
stdin
Standard input is empty
stdout
Compares pointers value of pointers, not values pointed to. Won't work
Found pointer, because this is one that was inserted in vector
Found because ad-hoc lambda function compares by value