C++中std::count函數(shù)介紹和使用場景
1. 函數(shù)介紹
std::count
是C++標(biāo)準(zhǔn)庫中的一個(gè)算法,用于計(jì)算給定值在指定范圍內(nèi)出現(xiàn)的次數(shù)。它的原型如下:
template <class InputIt, class T> size_t count(InputIt first, InputIt last, const T& value);
其中,first
和last
表示范圍的起始和結(jié)束迭代器,value
表示要查找的值。函數(shù)返回一個(gè)size_t
類型的值,表示value
在指定范圍內(nèi)出現(xiàn)的次數(shù)。
2. 使用場景
std::count
函數(shù)在以下場景中非常有用:
2.1 統(tǒng)計(jì)數(shù)組中某個(gè)元素的出現(xiàn)次數(shù)
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> nums = {1, 2, 3, 4, 5, 2, 3, 2}; int target = 2; size_t count = std::count(nums.begin(), nums.end(), target); std::cout << "The number " << target << " appears " << count << " times in the array." << std::endl; return 0; }
輸出結(jié)果:
The number 2 appears 3 times in the array.
2.2 統(tǒng)計(jì)字符串中某個(gè)字符的出現(xiàn)次數(shù)
#include <iostream> #include <string> #include <algorithm> int main() { std::string str = "hello world"; char target = 'l'; size_t count = std::count(str.begin(), str.end(), target); std::cout << "The character '" << target << "' appears " << count << " times in the string." << std::endl; return 0; }
輸出結(jié)果:
The character 'l' appears 3 times in the string.
2.3 統(tǒng)計(jì)容器中某個(gè)元素的出現(xiàn)次數(shù)
#include <iostream> #include <vector> #include <algorithm> #include <set> int main() { std::vector<int> nums = {1, 2, 3, 4, 5, 2, 3, 2}; int target = 2; size_t count = std::count(nums.begin(), nums.end(), target); std::cout << "The number " << target << " appears " << count << " times in the vector." << std::endl; std::set<int> s = {1, 2, 3, 4, 5, 2, 3, 2}; count = std::count(s.begin(), s.end(), target); std::cout << "The number " << target << " appears " << count << " times in the set." << std::endl; return 0; }
輸出結(jié)果:
The number 2 appears 3 times in the vector.
The number 2 appears 3 times in the set.
3. 總結(jié)
std::count
函數(shù)是一個(gè)非常實(shí)用的算法,它可以幫助我們快速統(tǒng)計(jì)給定值在指定范圍內(nèi)的出現(xiàn)次數(shù)。無論是統(tǒng)計(jì)數(shù)組、字符串還是容器中的元素出現(xiàn)次數(shù),都可以使用std::count
函數(shù)輕松實(shí)現(xiàn)。
到此這篇關(guān)于C++中std::count函數(shù)介紹和使用場景的文章就介紹到這了,更多相關(guān)C++ std::count函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C語言實(shí)現(xiàn)數(shù)組的循環(huán)左移,右移,翻轉(zhuǎn)的示例
今天小編就為大家分享一篇C語言實(shí)現(xiàn)數(shù)組的循環(huán)左移,右移,翻轉(zhuǎn)的示例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07C語言完整實(shí)現(xiàn)12種排序算法(小結(jié))
本文主要介紹了C語言完整實(shí)現(xiàn)12種排序算法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-05-05C++保存txt文件實(shí)現(xiàn)方法代碼實(shí)例
這篇文章主要介紹了C++保存txt文件實(shí)現(xiàn)方法代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-11-11Opencv實(shí)現(xiàn)聯(lián)合雙邊濾波
這篇文章主要為大家詳細(xì)介紹了Opencv實(shí)現(xiàn)聯(lián)合雙邊濾波,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-10-10解析C++編程中virtual聲明的虛函數(shù)以及單個(gè)繼承
這篇文章主要介紹了C++編程中virtual聲明的虛函數(shù)以及單個(gè)繼承,剖析虛函數(shù)和單個(gè)基類所能夠繼承的成員,要的朋友可以參考下2016-01-01