How to check the value exists in a C ++ stl vector and apply a function to each element of the vector?

I have two questions related to the vector class of the standard library in C ++.

  • How to check if a value exists in a vector (say, an integer)?

    What I want in words is as follows: "if an integer already exists in the vector, the next one, otherwise add it to the end of the vector."

  • How to apply a function that contains arguments for each element of a vector? (It seems I can not do this with for_each)

    In words: "for each element z in the vector MyAddFn (i, j) is used"

... or maybe I'm not on the right path with the container of the stl vector sequence, and should I define my own iterator?

+4
source share
3 answers

1)

std::find(v.begin(), v.end(), 5) == v.end() // checks that vector<int> v has no value 5.

2) Use, for example, the new C ++ 11 std :: bind, but for real advice I need more context to use MyAddFn.

+9
source

For 1, use std :: find . If the element does not exist, it returns the iterator to the end. In this case, add the item.

+1
source

Second question. You can use an object instead of a function:

 #include <vector> #include <algorithm> class apply_me { int multiplicator_; public: apply_me(const int multiplicator) : multiplicator_(multiplicator) {}; int operator ()(const int element) const { return element*multiplicator_; }; }; int main() { std::vector<int> v; std::transform(v.begin(), v.end(),v.begin(), apply_me(3)); } 
+1
source

All Articles