Check if element is in the list (contains)

后端 未结 7 2129
南笙
南笙 2021-01-31 14:38

I\'ve got a list of elements, say, integers and I want to check if my variable (another integer) is one of the elements from the list. In python I\'d do:

my_list         


        
7条回答
  •  忘掉有多难
    2021-01-31 15:16

    std::list does not provide a search method. You can iterate over the list and check if the element exists or use std::find. But I think for your situation std::set is more preferable. The former will take O(n) time but later will take O(lg(n)) time to search.

    You can simply use:

    int my_var = 3;
    std::set mySet {1, 2, 3, 4};
    if(mySet.find(myVar) != mySet.end()){
          //do whatever
    }
    

提交回复
热议问题