<kbd id="m0mea"><tt id="m0mea"></tt></kbd>
  • <s id="m0mea"><code id="m0mea"></code></s>
    <tbody id="m0mea"><u id="m0mea"></u></tbody><rt id="m0mea"><menu id="m0mea"></menu></rt>
  • <legend id="m0mea"><input id="m0mea"></input></legend>

    C++vector中如何查找某個元素是否存在?
    2022-09-06 22:38:41

    更普遍的講,我們對于vector內元素的需求不同,因此操作也有差異

    1. std::binary_search
    //先對vector進行排序,再使用二分查找,時間復雜度為O(logn)
    //注意在C++中也有sort函數,與python不同的是,它需要兩個參數,分別是vector的開頭元素,和vector的結尾元素
    sort(v.begin(), v.end());
    //這里的key就是我們要確認是否存在于vector中的元素
    if (std::binary_search(v.begin(), v.end(), key))
    //若存在,返回true;不存在返回false
    
    1. std::find
      該方法優點是,找到目標元素后立即返回,很快!
    #include <iostream>
    #include <vector>
    #include <algorithm>
    
    using std::vector;
    using std::count;
    using std::cout;
    using std::endl;
    
    int main()
    {
    		vector<int> v{ 4, 7, 9, 1, 2, 5 };
    		int key = 2;
    		
    		if (std::find(v.begin(), v.end(), key) != v.end())
    		{
    				cout << "Element found" << endl;
    		}
    		else
    		{
    				cout << "Element NOT found" << endl;
    		}
    		
    		return 0;
    }
    
    
    1. std::cout
      與find相對應,cout是在遍歷所有元素后才返回
      代碼只需要將上述條件語句改為if (count(v.begin(), v.end(), key))即可

    本文摘自 :https://www.cnblogs.com/


    更多科技新聞 ......

    日本成人三级A片
    <kbd id="m0mea"><tt id="m0mea"></tt></kbd>
  • <s id="m0mea"><code id="m0mea"></code></s>
    <tbody id="m0mea"><u id="m0mea"></u></tbody><rt id="m0mea"><menu id="m0mea"></menu></rt>
  • <legend id="m0mea"><input id="m0mea"></input></legend>