count(vs2010版本)
- 引言
这是我学习总结<algorithm>第九篇,count函数。有人会说,你老是用vs2010测试,vs别的版本代码都不能用,还学这个干么!其实我觉得要促进C++和algorithm的发展,应该了解现在的C++和algorithm,不了解又怎么知道哪有缺陷,了解不是目的,但是不可或缺。
- 作用
count 的作用是计算具有连续地址的一堆数据中某个元素的个数,返回值就是指定元素的个数。
- 原理
template <class InputIterator, class T>
typename iterator_traits<InputIterator>::difference_type
count (InputIterator first, InputIterator last, const T& val)
{
typename iterator_traits<InputIterator>::difference_type ret = 0;
while (first!=last) {
if (*first == val) ++ret;
++first;
}
return ret;
}
- 实验
在数据集合里
{10,20,30,30,20,10,10,20}分别计算10和20的个数
- 代码
test.cpp
#include <iostream> // std::cout
#include <algorithm> // std::count
#include <vector> // std::vector
int main ()
{
// counting elements in array:
int myints[8] = {10,20,30,30,20,10,10,20}; // 8 elements
int mycount = std::count (myints, myints+8, 10);
std::cout << "10 appears " << mycount << " times.\n";
// counting elements in container:
std::vector<int> myvector (myints, myints+8);
mycount = std::count (myvector.begin(), myvector.end(), 20);
std::cout << "20 appears " << mycount << " times.\n";
system("pause");
return 0;
}
template <class InputIterator, class T>
typename iterator_traits<InputIterator>::difference_type
count (InputIterator first, InputIterator last, const T& val)
{
typename iterator_traits<InputIterator>::difference_type ret = 0;
while (first!=last) {
if (*first == val) ++ret;
++first;
}
return ret;
}
#include <iostream> // std::cout
#include <algorithm> // std::count
#include <vector> // std::vector
int main ()
{
// counting elements in array:
int myints[8] = {10,20,30,30,20,10,10,20}; // 8 elements
int mycount = std::count (myints, myints+8, 10);
std::cout << "10 appears " << mycount << " times.\n";
// counting elements in container:
std::vector<int> myvector (myints, myints+8);
mycount = std::count (myvector.begin(), myvector.end(), 20);
std::cout << "20 appears " << mycount << " times.\n";
system("pause");
return 0;
}