Search code examples
pythonc++c++11stl-algorithm

implementing python's 'if X in List' in C++


We have an array object in C++, and a value. We want to control this value have in array or not have in array. How we can do this?


Solution

  • A little example using std::find()

    #include <array>
    #include <iostream>
    #include <algorithm>
    
    int main()
     {
       std::array<int, 5> a1 { { 2, 3, 5, 7, 11 } };
    
       std::cout << "8 is in a1 ? "
          << (a1.cend() != std::find(a1.cbegin(), a1.cend(), 8)) << std::endl;
    
       std::cout << "7 is in a1 ? "
          << (a1.cend() != std::find(a1.cbegin(), a1.cend(), 7)) << std::endl;
    
       return 0;
     }
    

    Can work with every container that implement or support begin() and end() (or better, cbegin() and cend())