6 Respuestas
+ 4
Opixelum ,
There is a function named find() in <algorithm> header. It returns an iterator to the element if it's found. otherwise it returns iterator to end of vector. Now you just need to check if returned value is equal to vector.end() if it's then element doesn't exist in vector.
I have wrapped this logic in a small function vector_contains.
#include <iostream>
#include <algorithm>
template <class T>
bool vector_contains(std::vector<T>& v, T& e){
if(std::find(v.begin(),
v.end(),e)!= v.end()){
return true;
}
return false;
}
int main() {
std::vector v{2,5,854,75,1,7,41,1};
std::cout<<std::boolalpha
<<vector_contains(v,3)<<std::endl;
std::cout<<std::boolalpha
<<vector_contains(v,1);
return 0;
}
https://en.cppreference.com/w/cpp/algorithm/find
+ 4
std::find works for strings too.
std::string also has .begin() and .end() methods.
std::string str = "loremIpsum";
if(std::find(str.begin(), str.end() , 'o') != str.end()){
//found!
}
+ 3
Opixelum ,
There is no in operator but there are functions in STL that can be used to get the task done.
Do you want to check existence of element in std::vector, std::array etc or in a char std::string ? or are you using some other data structure? Please provide more details.
+ 2
Иван Чикyнов ,
There is no `in` operator in C++.
+ 2
🇮🇳Omkar🕉 I added details in my question.
+ 1
oh okay, and is it the same function for string too ?