std::count 函式

胖柚の工作室發表於2024-04-21

1. 函式介紹

std::count是C++標準庫中的一個演算法,用於計算給定值在指定範圍內出現的次數。它的原型如下:

template <class InputIt, class T>
size_t count(InputIt first, InputIt last, const T& value);

其中,firstlast表示範圍的起始和結束迭代器,value表示要查詢的值。函式返回一個size_t型別的值,表示value在指定範圍內出現的次數。

2. 使用場景

std::count函式在以下場景中非常有用:

2.1 統計陣列中某個元素的出現次數

#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;
}

輸出結果:

The number 2 appears 3 times in the array.

2.2 統計字串中某個字元的出現次數

#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;
}

輸出結果:

The character 'l' appears 3 times in the string.

2.3 統計容器中某個元素的出現次數

#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;
}

輸出結果:

The number 2 appears 3 times in the vector.
The number 2 appears 3 times in the set.

3. 總結

std::count函式是一個非常實用的演算法,它可以幫助我們快速統計給定值在指定範圍內的出現次數。無論是統計陣列、字串還是容器中的元素出現次數,都可以使用std::count函式輕鬆實現。

轉載自[C++] 基礎教程 - std::count函式介紹和使用場景

相關文章