How to find out if an item is present in a std::vector?

后端 未结 18 2532
滥情空心
滥情空心 2020-11-22 05:31

All I want to do is to check whether an element exists in the vector or not, so I can deal with each case.

if ( item_present )
   do_this();
else
   do_that(         


        
18条回答
  •  日久生厌
    2020-11-22 06:04

    Use find from the algorithm header of stl.I've illustrated its use with int type. You can use any type you like as long as you can compare for equality (overload == if you need to for your custom class).

    #include 
    #include 
    
    using namespace std;
    int main()
    {   
        typedef vector IntContainer;
        typedef IntContainer::iterator IntIterator;
    
        IntContainer vw;
    
        //...
    
        // find 5
        IntIterator i = find(vw.begin(), vw.end(), 5);
    
        if (i != vw.end()) {
            // found it
        } else {
            // doesn't exist
        }
    
        return 0;
    }
    

提交回复
热议问题