C++ count_if/erase/remove_if 用法详解
每次使用这几个算法时都要去查CPP reference,为了能够加深印象,整理一下基本应用。
cout/cout_if: return the number of elements satisfying the condition.
count( InputIt first, InputIt last, const T &value ); // counts the elements that are equal to value
.
count_if( InputIt first, InputIt last, UnaryPredicate p ); //counts elements for which predicate p
returns true.
eg.
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
std::vector<int> v{ 1, 2, 3, 4, 4, 3, 7, 8, 9, 10 };
// determine how many integers in a std::vector match a target value.
int target1 = 3;
int target2 = 5;
int num_items1 = std::count(v.begin(), v.end(), target1);
int num_items2 = std::count(v.begin(), v.end(), target2);
std::cout << "number: " << target1 << " count: " << num_items1 << '\n';
std::cout << "number: " << target2 << " count: " << num_items2 << '\n';
// use a lambda expression to count elements divisible by 3.
int num_items3 = std::count_if(v.begin(), v.end(), [](int i){return i % 3 == 0;});
std::cout << "number divisible by three: " << num_items3 << '\n';
}
remove_if/erase 通常一起用。(使用string的erase成员函数举例)
关于remove_if/remove 移除性算法来说,是根据元素值或某一准则,在一个区间内移除某些元素。这些算法并不能改变元素的数量,它们只是以逻辑上的思考,将原本置于后面的“不移除元素”向前移动,
覆盖那些被移除元素而已,它们都返回新区间的逻辑终点(也就是最后一个“不移除元素”的下一位置)。
ForwardIt remove( ForwardIt first, ForwardIt last, const T& value );// Removes all elements that are equal to value
.
ForwardIt remove_if( ForwardIt first, ForwardIt last, UnaryPredicate p );//Removes all elements for which predicate p
returns true.
- 返回的是变动后的序列的新逻辑终点,也就是最后一个未被移除的元素的下一个位置。
- 未被移除的元素在相对次序上保持不变。
- 调用者在调用此算法之后,应保证从此采用返回的新逻辑终点,而不再使用原始终点end;
eg.
#include <algorithm>
#include <string>
#include <iostream>
#include <cctype>
int main()
{
std::string str1 = "Text with some spaces";
str1.erase(std::remove(str1.begin(), str1.end(), ' '),
str1.end());
std::cout << str1 << '\n';
std::string str2 = "Text\n with\tsome \t whitespaces\n\n";
str2.erase(std::remove_if(str2.begin(),
str2.end(),
[](char x){return std::isspace(x);}),
str2.end());
std::cout << str2 << '\n';
}
此例中使用的是
最新文章
- 在HTML中使用JavaScript元素
- SSRS 报表点击 Preview 显示失败
- [WPF]Slider控件常用方法
- 【BZOJ-3174】拯救小矮人 贪心 + DP
- Unity3D特效-场景淡入淡出
- Apache-Shiro+Zookeeper系统集群安全解决方案之缓存管理
- 使用MySQL数据库
- Spring AOP切面
- 关于bootstrap--网格系统
- 关于android中postDelayed方法的讲解
- stm32串口接收发送数据处理
- [LeetCode] Cheapest Flights Within K Stops K次转机内的最便宜的航班
- [Postman]定制Postman(4)
- Python_内置函数之round的幺蛾子
- PHP中empty,is_null,isset的区别
- 在Android上启用Kiosk模式
- 尚硅谷面试第一季-12Linux常用服务类相关命令
- lua 工具类(二)
- 使用web api开发微信公众号,调用图灵机器人接口(二)
- SVN checkout 出的项目在PHPstorm中打开没有subversion(SVN)选项按钮怎么办?