C++ 元素计数 count()
algostuff.hpp
#ifndef ALGOSTUFF_HPP
#define ALGOSTUFF_HPP
#include <array>
#include <vector>
#include <deque>
#include <list>
#include <forward_list>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <algorithm>
#include <iterator>
#include <functional>
#include <numeric>
#include <iostream>
#include <string>
//集合中添加元素
template <typename T>
inline void INSERT_ELEMENTS(T& coll, int first, int last)
{
for (int i = first; i <= last; ++i)
{
coll.insert(coll.end(), i);
}
}
//输出集合中的元素
template <typename T>
inline void PRINT_ELEMENTS(const T& coll, const std::string & optcstr = "")
{
std::cout << optcstr;
for (auto elem : coll)
{
std::cout << elem << " ";
}
std::cout << std::endl;
}
//输出Map中的元素
template<typename T>
inline void PRINT_MAPPED_ELEMENTS(const T& coll, const std::string& optcstr = "")
{
std::cout << optcstr;
for (auto elem : coll)
{
std::cout << "[" << elem.first << "," << elem.second << "] ";
}
std::cout << std::endl;
}
#endif // !ALGOSTUFF_HPP
testCount.cpp
#include "algostuff.hpp"
using namespace std;
int main()
{
vector<int> vec1;
int num1 = 0;
INSERT_ELEMENTS(vec1, 1, 9);
PRINT_ELEMENTS(vec1,"vec1: ");
num1 = count(vec1.cbegin(),vec1.cend(),4);
cout << "number of elements equal to 4: " << num1 << endl;
num1 = count_if(vec1.cbegin(),vec1.cend(),
[](int elem1) {
return elem1 % 2 == 0;
});
cout << "number of elements with even value: " << num1 << endl;
num1 = count_if(vec1.cbegin(),vec1.cend(),
[](int elem1) {
return elem1 > 4;
});
cout << "number of elements greater than 4: " << num1 << endl;
system("pause");
return 0;
}
vec1: 1 2 3 4 5 6 7 8 9
number of elements equal to 4: 1
number of elements with even value: 4
number of elements greater than 4: 5
请按任意键继续. . .
代码参考:C++标准库(第2版)
原文链接: https://www.cnblogs.com/herd/p/12141776.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/191298
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!