0

After the following start:

#include <vector>
#include <algorithm>

struct OBJECT{
        char VALUE;
        int COUNTER;
}
vector <OBJECT> MyCollection;   
vector <OBJECT> ::iterator begin,end;
char TEMP;

begin=MyCollection.begin();
end=MyCollection.end();

...i want to use the Find() function to search the VALUE fields of the OBJECT entries in the vector like:

find (begin, end, TEMP);

(and later on succes do a COUNTER++ on the found OBJECT).

This is not possible by default because TEMP is not of OBJECT type but a char.

Any ideas?

As a student, i have not been able to translate the suggestions to working code, so wrote my own solution around the .at() method and deleted the iterators begin and end.

int MyCollectionIterator=MyCollection.size(); 

while(1){
  if(MyCollectionIterator){ 
    if( MyCollection.at(--MyCollectionIterator).VALUE==TEMP ){
          MyCollection[MyCollectionIterator].COUNTER++; 
          break;
    }
  }else break;
} 

1 Answers1

1

You want to use std::find_if something like this:

struct is_equal {
    char target_;
    isEqual(char target) : target_(target) {};
    bool operator () (const OBJECT& obj) {
        return obj.VALUE == target_;
    };
};
char target_char = // set this to the character you're looking for
vector<OBJECT>::iterator it = std::find_if(begin, end, is_equal(target_char));
if (it != end) {
    it->COUNTER++;
}
Paul Evans
  • 27,315
  • 3
  • 37
  • 54