Python’s « in », « not in » operators Cpp equivalent | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Python’s « in », « not in » operators Cpp equivalent

Are there cpp equivalents for the "in" and the "not in" python operators ? It's for checking existence of elements in a vector.

13th Dec 2020, 11:32 AM
Opixelum
Opixelum - avatar
6 Answers
+ 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
13th Dec 2020, 12:10 PM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
+ 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! }
13th Dec 2020, 12:17 PM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
+ 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.
13th Dec 2020, 11:50 AM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
+ 2
Иван Чикyнов , There is no `in` operator in C++.
13th Dec 2020, 11:46 AM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
+ 2
🇮🇳Omkar🕉 I added details in my question.
13th Dec 2020, 11:54 AM
Opixelum
Opixelum - avatar
+ 1
oh okay, and is it the same function for string too ?
13th Dec 2020, 12:13 PM
Opixelum
Opixelum - avatar