I have two questions related to the vector class of the standard library in C++.
How can I check whether a value (let's say of an integer) already exists in a vector?
What I want in words is as follows: "if the integer already exists in the vector, next one, else add it at the end of the vector."
How do I apply a function that holds arguments to every element in the vector? (It seems I can't do that with for_each)
In words: "for each z element in the vector apply MyAddFn(i,j)"
... or maybe I'm not on the right track with the stl vector sequence container, and I should define my own iterator?
1)
std::find(v.begin(), v.end(), 5) == v.end() // checks that vector<int> v has no value 5.
2) Use new C++11 std::bind for example, but for real advice i need more context of use MyAddFn.
For 1, use std::find algorithm. If the element does not exist, it returns the iterator to the end. In that case, add the element.
2nd question. You can use object instead of 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));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.