With these definitions:
vector<char> a = {'a', 'b', 'c', 'd', 'e', 'f' /*...*/};
char ch = 'x';
You can easily go for the following, starting after the first char (+1
) and ending ignoring the two last elements (-2
):
if (any_of(a.cbegin()+1, a.cend()-2, [&ch](auto &x){return x==ch; }))
cout << "found !"<<endl;
else cout << "not found! "<<endl;
You can also use the more classical std::find()
in the <algorithm>
library:
if (std::find(a.cbegin(), a.cend(), ch) !=a.cend())
...
If you want to start at a given offset or end ignoring some trailing elements, you can go iterator math on the start or end iterator:
if (std::find(a.cbegin()+3, a.cend(), ch) != a.cend())
...
If you do this often, and you're not intereste where in the vector the element is found, you could consider the following function:
template <class U, class W>
bool myfind (const U &v, size_t starto, size_t endo, const W& x) {
if (starto>=endo || endo>=v.size())
return false;
return std::find(v.begin()+starto, v.begin()+endo, x) != v.begin()+endo;
}
If you can go for std::string
rather than std::vector
, you could use the member function find()
which can take an offset as argument.