The Ranges Library (2) --- C++20

The Ranges Library (2) — C++20

比较stdstd::ranges算法

比较一下std::sortstd::ranges::sort

  • std::sort
template< class RandomIt >
constexpr void sort( RandomIt first, RandomIt last );template< class ExecutionPolicy, class RandomIt >
void sort( ExecutionPolicy&& policy,RandomIt first, RandomIt last );template< class RandomIt, class Compare >
constexpr void sort( RandomIt first, RandomIt last, Compare comp );template< class ExecutionPolicy, class RandomIt, class Compare >
void sort( ExecutionPolicy&& policy,RandomIt first, RandomIt last, Compare comp );
  • std::ranges::sort
template <std::random_access_iterator I, std::sentinel_for<I> S,class Comp = ranges::less, class Proj = std::identity>
requires std::sortable<I, Comp, Proj>
constexpr I sort(I first, S last, Comp comp = {}, Proj proj = {});template <ranges::random_access_range R, class Comp = ranges::less, class Proj = std::identity>
requires std::sortable<ranges::iterator_t<R>, Comp, Proj>
constexpr ranges::borrowed_iterator_t<R> sort(R&& r, Comp comp = {}, Proj proj = {});

你观察一下第二个重载,你会发现, 他需一个支持ranges::random_access_range的容器

std::forward_liststd::liststd::dequestd::arraystd::vector
std::ranges::random_access_range

一个谓词 Comp(返回bool的可调用对象),一个std::identity,Comp默认是less,Prog是std::identity :就是参数本身,本质是使用完美转发, 按照Prog将一个集合映射到子集

#include <iostream>
#include <ranges>
#include <vector>
#include <algorithm>using namespace std;struct PhoneBookEntry
{std::string name;int number;
};void printPhoneBook(const std::vector<PhoneBookEntry>& phoneBook)
{for (const auto& entry : phoneBook) std::cout << "(" << entry.name << ", " << entry.number << ")";std::cout << "\n\n";
}int main()
{std::cout << '\n';std::vector<PhoneBookEntry> phoneBook{{"Brown", 111}, {"Smith", 444},{"Grimm", 666}, {"Butcher", 222},{"Taylor", 555}, {"Wilson", 333}};std::ranges::sort(phoneBook, {}, &PhoneBookEntry::name); // 按姓名升序printPhoneBook(phoneBook);std::ranges::sort(phoneBook, std::ranges::greater(),&PhoneBookEntry::name); //按姓名降序printPhoneBook(phoneBook);std::ranges::sort(phoneBook, {}, &PhoneBookEntry::number); // 按号码升序printPhoneBook(phoneBook);std::ranges::sort(phoneBook, std::ranges::greater(),&PhoneBookEntry::number); // 按号码降序printPhoneBook(phoneBook);
}

image-20220616153237923

如果你有更加复杂的要求,可以使用lambda函数这样的可调用对象

#include <iostream>
#include <ranges>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;struct PhoneBookEntry
{std::string name;int number;
};void printPhoneBook(const std::vector<PhoneBookEntry>& phoneBook)
{for (const auto& entry : phoneBook) std::cout << "(" << entry.name << ", " << entry.number << ")";std::cout << "\n\n";
}int main()
{std::cout << '\n';std::vector<PhoneBookEntry> phoneBook{{"Brown", 111}, {"Smith", 444},{"Grimm", 666}, {"Butcher", 222},{"Taylor", 555}, {"Wilson", 333}};std::ranges::sort(phoneBook, {}, [](auto p) { return p.name; });printPhoneBook(phoneBook);std::ranges::sort(phoneBook, [](auto p, auto p2){return std::to_string(p.number) + p.name <std::to_string(p2.number) + p2.name;});printPhoneBook(phoneBook);
}

直接查看key和value

可以直接查看map中的 key 和 value

#include <iostream>
#include <ranges>
#include <vector>
#include <algorithm>
#include <string>
#include <unordered_map>using namespace std;int main()
{std::unordered_map<std::string, int> m{{"李宁", 12}, {"张三", 34}, {"张杰", 23}};auto names = std::views::keys(m);cout << "keys: ";for (auto name : names){cout << name << " ";}cout << endl;auto ages = std::views::values(m);cout << "values: ";for (auto age : ages){cout << age << " ";}cout << " ";
}

image-20220616162131843

但我们还有更加灵活的方式,使用lambda函数来完成一些更复杂的逻辑

Function Composition

上一篇文章中有提及, 但不是很复杂, 我们实现一些更复杂的逻辑

#include <iostream>
#include <ranges>
#include <vector>
#include <algorithm>
#include <string>
#include <unordered_map>using namespace std;int main()
{std::unordered_map<std::string, int> m{{"李宁", 12}, {"张三", 34}, {"张杰", 23}, {"西施", 18}, {"修勾", 4}};auto names = std::views::keys(m);cout << "keys: ";for (auto name : names){cout << name << " ";}cout << endl;auto ages = std::views::values(m);cout << "values: ";for (auto age : ages){cout << age << " ";}cout << " " << endl;std::cout << "张 开头的姓名: ";auto fistZ = [](const std::string& name) { return name.find("张", 0) == 0; };for (const auto& name : std::views::keys(m) | std::views::filter(fistZ)){cout << name << " ";}cout << endl;
}

image-20220616163534876

| 是一个语法糖, C(R)等价于 R | C

auto rev1 = std::views::reverse(std::views::keys(m));
auto rev2 = std::views::keys(m) | std::views::reverse;
auto rev3 = freqWord | std::views::keys | std::views::reverse;

Lazy Evaluation 惰性执行

上一篇文章已经介绍了

自定义View

#include <ranges>
#include <vector>
#include <iostream>template <class T, class A>
class VectorView : public std::ranges::view_interface<VectorView<T, A>>
{
public:VectorView() = default;VectorView(const std::vector<T, A>& vec) :m_begin(vec.cbegin()), m_end(vec.cend()){}auto begin() const { return m_begin; }auto end() const { return m_end; }
private:typename std::vector<T, A>::const_iterator m_begin{}, m_end{};
};int main()
{std::vector<int> v = {1, 4, 9, 16};VectorView view_over_v{v};// We can iterate with begin() and end().for (int n : view_over_v){std::cout << n << ' ';}std::cout << '\n';// We get operator[] for free when inheriting from view_interface// since we satisfy the random_access_range concept.for (std::ptrdiff_t i = 0; i < view_over_v.size(); i++){std::cout << "v[" << i << "] = " << view_over_v[i] << '\n';}
}

image-20220616173540337

perator[] for free when inheriting from view_interface
// since we satisfy the random_access_range concept.
for (std::ptrdiff_t i = 0; i < view_over_v.size(); i++)
{
std::cout << “v[” << i << "] = " << view_over_v[i] << ‘\n’;
}
}


[外链图片转存中...(img-wfU5FiLx-1655480994818)]

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/407981.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

react(79)--ant design确认框

<Popconfirmplacement"rightBottom"title{text}onConfirm{confirm}okText"Yes"cancelText"No"><Button>RB</Button></Popconfirm>

程序中的得与失

俗话说&#xff0c;舍得&#xff0c;有舍便有得&#xff0c;程序或许和世间万物一个样&#xff0c;讲究阴阳平衡。或许您写程序过程中&#xff0c;得到一颗歪脖树&#xff0c;却放弃了一大片大森林&#xff0c;能正确的取舍矛盾体双方的关系&#xff0c;或许是您扎实功底的体现…

[转]新东方老师上课讲的笑话(太有才了)

[张洪伟] 起名字的问题&#xff1a;中西方都不愿意以鲜花、野草起名字&#xff0c;什么牡丹玫瑰&#xff0c;小红小翠了&#xff0c;一听就变味了&#xff1b;张建、李建&#xff0c;但不能叫范建&#xff08;贱&#xff09;了&#xff1b;北京以前有个建&#xff08;贱&#x…

c/c++面试试题(三)

慧通&#xff1a; 什么是预编译何时需要预编译&#xff1a;&#xff11;、总是使用不经常改动的大型代码体。 &#xff12;、程序由多个模块组成&#xff0c;所有模块都使用一组标准的包含文件和相同的编译选项。在这种情况下&#xff0c;可以将所有包含文件预编译为一个预编译…

mysql安装使用--2 用户管理

1 修改mysql.user表 添加用户 mysql> INSERT INTO mysql.user (Host,User,Password) VALUES (\%\,\system\, PASSWORD(\manager\)); mysql> FLUSH PRIVILEGES 2 create 和 grant命令省略 3 user表内容 MySQL用户名由两部分组成&#xff1a;(user, host)&#xff0c;二者…

constexpr if --- C++ 20

constexpr if — C 20 constexpr if 可以让我们实现条件编译 template <typename T> auto getResult(T t) {if constexpr (std::is_integral_v<T>)return *t;elsereturn t; }如果T是intergral类型,执行第一个分支,否则执行第二个分支 还记得前文写过的模板元编程…

WPF中的动画

WPF中的动画 周银辉动画无疑是WPF中最吸引人的特色之一&#xff0c;其可以像Flash一样平滑地播放并与程序逻辑进行很好的交互。这里我们讨论一下故事板。在WPF中我们采用Storyboard&#xf…

c/c++面试试题(四)

華為1、局部变量能否和全局变量重名&#xff1f;答&#xff1a;能&#xff0c;局部会屏蔽全局。要用全局变量&#xff0c;需要使用"::"局部变量可以与全局变量同名&#xff0c;在函数内引用这个变量时&#xff0c;会用到同名的局部变量&#xff0c;而不会用到全局变量…

[访问系统] Api_Win32_Mac类工具包 (转载)

点击下载 Api_Win32_Mac.zip using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices;namespace BaseFunction {class API{[DllImport("kernel32")]//内存public static extern void GlobalM…

constexpr 函数

constexpr 函数 — C 20 constexpr double pi 3.14;constexpr允许你在编译时使用典型的C函数语法进行编程,但这并不意味之constexpr只和编译期有关 constexpr函数可以在编译期运行,也可以在运行时运行 但在以下情况constexpr函数必须在编译期运行: constexpr函数在编译的上…

react(82)--方法写在effects里面

effects: {*addOrUpdateAssistActivity({ payload, callback }, { call }) {try {const res yield call(addOrUpdateAssistActivity, payload);if (callback && typeof callback function) {yield callback(res);}} catch (error) {console.log(error);}},

让VS2005用起来更顺手

1. 在解决方案资源管理器中跟踪活动项VS2005 工具 选项 项目和解决方案 常规&#xff0c;把“在解决方案资源管理器中跟踪活动项”打勾。2. 显示行号VS2005 工具 选项 文本编辑器 C#&#xff0c;把“行号”打勾。或者 VS2005 工具 选项 文本编辑器 所有语言&…

C++面试题目(五)

思科1. 用宏定义写出swap&#xff08;x&#xff0c;y&#xff09;#define swap(x, y)/x x y;/y x - y;/x x - y;2.数组a[N]&#xff0c;存放了1至N-1个数&#xff0c;其中某个数重复一次。写一个函数&#xff0c;找出被重复的数字.时间复杂度必须为o&#xff08;N&#xff…

如何利用脚本方法清除文本框中汉字,从而保留英文字母和数字等

脚本方法如下&#xff1a; <script language"javascript" type"text/javascript"> function RemoveChineseCharacters(teleriktextboxID) {var textboxinput document.getElementById(teleriktextboxID);var textboxinputhidden document.g…

react(83)--filter

let newarr friendTableSource.filter(function(item, index, arr0) {return item.code ! val;});

constexpr和consteval --- C++ 20

constexpr和consteval — C 20 标准库容器和算法库对constexpr 的应用 C20 中大量的算法和容器可以使用constexpr,这意味着你甚至可以再编译期vector<int>进行排序 Algorithms library - cppreference.com 如下: #include <iostream> #include <ranges>…

西藏攻略集锦

西藏旅游局针对初此进藏旅游的驴友提供实用资讯本文为西藏旅游局针对初次进藏的驴友提供实用资讯&#xff0c;供各位参考。 1、什么是高原反应&#xff1f;高原反应有哪些症状&#xff1f; 高原反应是人到达一定海拔高度后&#xff0c;身体为适应因海拔高度…

将select中的项从一个移动到另一个select中

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns"http://www.w3.org/1999/xhtml" ><head> <title>将select中的项互相移动…

函数模板(参考《C++ Templates 英文版第二版》)

函数编程(参考《C Templates 英文版第二版》) Chapter 1 函数模板 1.1 一窥函数模板 template<class T> T max(T a, T b) {return b < a ? a : b; }#include "max1.hpp" #include <iostream> #include <string> #include <format>int…