《认清C++语言》のrandom_shuffle()和transform()算法

1STL中的函数random_shuffle()用来对一个元素序列进行重新排序(随机的),函数原型如下:

 

template<class RandomAccessIterator>

   void random_shuffle(

      RandomAccessIterator _First, //指向序列首元素的迭代器

      RandomAccessIterator _Last  //指向序列最后一个元素的下一个位置的迭代器

   );

template<class RandomAccessIterator, class RandomNumberGenerator>

   void random_shuffle(

      RandomAccessIterator _First,

      RandomAccessIterator _Last,

      RandomNumberGenerator& _Rand //调用随机数产生器的函数

   );

 

random_shuffle()是一个完全通用的算法,适用于内置数据类型和用户自定义类型。同时,由于STL算法不仅适用于容器,也适用于序列,因此,random_shuffle()算法可用于内置数组。

 

实例代码如下:

#include <iostream>

#include <vector>

#include <algorithm>

#include <string>

 

int main()

{

    //用于内置数据类型

    std::vector<int> vi;

    for(int i=0; i<100; i++)

    {

        vi.push_back(i);        

    }

   

    std::random_shuffle(vi.begin(), vi.end());

   

    std::vector<int>::iterator it;

    for(it=vi.begin(); it!=vi.end(); it++)

    {

        std::cout<<*it<<std::endl;                  

    }

   

    //用于用户自定义类型

    std::vector<std::string> vs;

    vs.push_back(std::string("Sunday"));

    vs.push_back(std::string("Monday"));

    vs.push_back(std::string("Tuesday"));

    vs.push_back(std::string("Wednesday"));

    vs.push_back(std::string("Thursday"));

    vs.push_back(std::string("Friday"));

    vs.push_back(std::string("Saturday"));

   

    std::random_shuffle(vs.begin(), vs.end());

   

    for(int i=0; i<7; i++)

    {

        std::cout<<vs[i]<<std::endl;       

    }

   

    //用于数组

    char arr[6] = {'a', 'b', 'c', 'd', 'e', 'f'};

    std::random_shuffle(arr, arr+6);

    for(int i=0; i<6; i++)

    {

        std::cout<<arr[i]<<" ";       

    }

    std::cout<<std::endl;

    system("pause");

    return 0;

}

 

2STL中的函数transform()用来遍历一个容器里面指定范围的元素,并对这些元素执行指定的操作,函数原型如下:

template<class InputIterator, class OutputIterator, class UnaryFunction>

   OutputIterator transform(

      InputIterator _First1, //元素起始位置的输入迭代器

      InputIterator _Last1, //元素结束位置的输入迭代器

      OutputIterator _Result, //执行指定操作的元素的起始位置的输出迭代器

      UnaryFunction _Func //执行的操作(函数)

   );

template<class InputIterator1, class InputIterator2, class OutputIterator,

   class BinaryFunction>

   OutputIterator transform(

      InputIterator1 _First1, //第一个操作范围的元素起始位置的输入迭代器

      InputIterator1 _Last1, //第一个操作范围的元素结束位置的输入迭代器

      InputIterator2 _First2, //第二个操作范围的元素起始位置的输入迭代器

      OutputIterator _Result, //最终范围的元素的起始位置的输出迭代器

      BinaryFunction _Func //执行的操作(函数)

   );

 

上面第一个版本的算法对区间[_First1, _Last1]中的每个元素应用函数_Func,并将每次_Func返回的结果存储到_Result中;

第二个版本的算法以类似的方式运行,但它期望获得两个序列并逐次调用一个处理成对元素的二元函数。

 

实例代码如下:

#include <vector>

#include <algorithm>

#include <functional>

#include <iostream>

 

// The function object multiplies an element by a Factor

template <typename T>

class MultiValue

{

private:

    T Factor;   //The value to multiply by

public:

    //Constructor initializes the value to multiply by

    MultiValue(const T& _val) : Factor(_val)

    {

    }

    //The function call for the element to be multiplied

    T operator()(T& elem) const

    {

        return elem*Factor;               

    }

};

 

int main()

{

    using namespace std;

    vector<int> v1, v2(7), v3(7);

    vector<int>::iterator it1, it2, it3;

   

    //Constructing vector v1;

    for(int i=-4; i<=2; i++)

    {

        v1.push_back(i);       

    }   

   

    cout<<"Original vector v1=(";

    for(it1=v1.begin(); it1!= v1.end(); it1++)

    {

        cout<<*it1<<" ";                   

    }

    cout<<")."<<endl;

   

    //Modifying the vector v1 in place

    transform(v1.begin(), v1.end(), v1.begin(), MultiValue<int>(2));

    cout<<"The elements of the vector v1 multiplied by 2 in place gives:"

        <<"/n v1mod=(";

    for(it1=v1.begin(); it1!=v1.end(); it1++)

    {

        cout<<*it1<<" ";                   

    }

    cout<<")."<<endl;

   

    //using transform to multiply each element by a factor of 5

    transform(v1.begin(), v1.end(), v2.begin(), MultiValue<int>(5));

   

    cout<<"Multiplying the elements of the vector v1mod/n"

        <<"by the factor 5 & copying to v2 gives:/n v2=(";

    for(it2=v2.begin(); it2!=v2.end(); it2++)

    {

        cout<<*it2<<" ";                   

    }

    cout<<")."<<endl;

   

    //The second version of transform used to multiply the

    //elements of the vectors v1mod & v2 pairwise

    transform(v1.begin(), v1.end(), v2.begin(), v3.begin(),

                          multiplies<int>());

    cout<<"Multiplying elements of the vectors v1mod and v2 pairwise "

        <<"gives:/n v3=( ";

    for(it3=v3.begin(); it3!=v3.end(); it3++)

    {

        cout<<*it3<<" ";

    }

    cout<<")."<<endl;

   

    system("pause");

    return 0;

}

 

程序运行后输出如下:

Original vector  v1 = ( -4 -3 -2 -1 0 1 2 ).
The elements of the vector v1 multiplied by 2 in place gives:
 v1mod = ( -8 -6 -4 -2 0 2 4 ).
Multiplying the elements of the vector v1mod
 by the factor 5 & copying to v2 gives:
 v2 = ( -40 -30 -20 -10 0 10 20 ).
Multiplying elements of the vectors v1mod and v2 pairwise gives:
 v3 = ( 320 180 80 20 0 20 80 ).

 

 

 

 

 

转载于:https://www.cnblogs.com/android-html5/archive/2010/09/07/2533985.html

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

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

相关文章

作为前端开发,如何高效学习 TypeScript

大家好&#xff0c;我是若川。有朋友跟我说最近面试前端候选人&#xff0c;问到关于 JavaScript 的一些少见误区问题&#xff0c;候选人很多都没回答上来&#xff0c;他很诧异&#xff0c;一个从国际大厂出来的面试者&#xff0c;竟然对 JavaScript 的一些误区问题都不了解。他…

figma下载_对于这10家公司,Figma是迈向新高度的起点

figma下载Hey everyone! In this post, we are highlighting 10 companies for which the use of Figma has become the starting point on the path to new heights. These are the use cases of problems and their solutions, where Figma played a decisive role.嘿大家&am…

mysql查询条件为or_使用mysql查询where条件里的or和and

为什么要着重讲这块内容呢?因为好多小伙伴都会混淆&#xff0c;要不就是不知道怎么组合使用&#xff0c;今天就给大家讲这部分内容干货&#xff0c;让大家半分钟看懂。AND、OR运算符的组合使用在WHERE子句中&#xff0c;通过AND、OR运算符可以同时连接多个条件&#xff0c;当然…

sql server(常用)

普通用法 //生成 uuid 并转为小写 select LOWER(SUBSTRING(uuid,1,8)-SUBSTRING(uuid,10,4)-SUBSTRING(uuid,15,4)-SUBSTRING(uuid,20,4)-SUBSTRING(uuid,25,12)) from (select cast(NEWID() as varchar(36)) as uuid) s //ea52a7bb-a2aa-44b8-be28-5ebc64defcf9//获取时分秒…

代码编写中会遇到的安全性问题

一、常用的攻击手段 1&#xff0e;脚本注入 漏洞描述&#xff1a; 脚本注入攻击在通过浏览器使用用户输入框插入恶意标记或脚本代码时发生。 如&#xff1a;某个输入框允许用户向数据存储中插入内容&#xff0c;如果将一段js脚本插入其中&#xff0c;则当其他用户使用或浏览此数…

TypeScript 原来可以这么香?!

先问一个问题&#xff0c;JavaScript有几种数据类型&#xff1f;number、string、boolean、null、undefined、symbol、bigint、object其中 bigint 是 ES2020 新增的数据类型&#xff0c;而早在 TS3.2 时便成为 TS 的标准&#xff0c;其实还有好多 ES 标准是 TS 率先提出的&…

java8新特性stream深入解析

2019独角兽企业重金招聘Python工程师标准>>> 继续java8源码的发烧热&#xff0c;越看越是有充实的感觉。 数据时代下的产物 Java顺应时代的发展推出的高效处理大量数据能力的api&#xff0c;它专注于对集合对象进行各种非常便利、高效的聚合操作&#xff0c;借助于同…

mysql内连接的自连接_mysql 内连接、外连接、自连接

一)内连接(等值连接)&#xff1a;查询客户姓名&#xff0c;订单编号&#xff0c;订单价格---------------------------------------------------select c.name,o.isbn,o.pricefrom customers c inner join orders owhere c.id o.customers_id;-------------------------------…

关于ASP.NET MVC

我是否要学习一下ASP.NET MVC呢&#xff1f;因爲从它刚发布的时候就已经初步的学习了一下&#xff0c;可是一直没有坚持下来。不过心里对于这份惦记&#xff0c;又让我始终放不下&#xff0c;看来应该抽个时间来系统的学习一下。 就这样吧&#xff0c;把自己的博客当成微博来使…

版式设计与创意 pdf_恋爱与版式

版式设计与创意 pdfSince its beginnings, Libération has been characterized by a very distinctive use of typeface, to such an extent that Libé has put its mark on fonts from across different eras, appropriating these in a certain way.小号因斯它的起点&…

移动网站开发——标记语言

移动互联网被称为“第五次科技革命”&#xff0c;而随着iPhone和Android等智能手机的日渐流行和iPad等平板电脑的出现&#xff0c;移动互联网的潜力和趋势也愈发显现&#xff0c;针对移动设备的网站开发越来越受到关注&#xff0c;国内很多公司也开始重视面向所有移动设备的网站…

mysql适配器_MySQL适配器PyMySQL详解

import pymysqlimport datainfoimport time#获取参数host datainfo.hostusername datainfo.usernamepassword datainfo.passworddatabase datainfo.dbprint()#测试数据库连接def testconnect():#打开数据库链接db pymysql.connect(host,username,password,database)#使用c…

获取当前Tomcat实例的端口

有时需要在当前代码中获取当前Server实例的端口号, 通过HttpServletRequest请求可以, 但有时也需要在没有请求的情况下获取到端口号. 用以下方法是可以获取到的: public int getHttpPort() {try {MBeanServer server;if (MBeanServerFactory.findMBeanServer(null).size() >…

前端技术未来三年前瞻性思考

大家好&#xff0c;我是若川。今天推荐云谦大佬的一篇好文章&#xff0c;值得收藏。点击下方卡片关注我、加个星标&#xff0c;或者查看源码等系列文章。学习源码整体架构系列、年度总结、JS基础系列习惯从业务场景、用户体验、研发速度、维护成本四个维度来看框架等前端技术&a…

微信临时素材接口_在接口中表达临时性

微信临时素材接口When interacting with today’s graphic user interfaces (GUI), we experience a sense of realism. As of now, certain aspects of realism (for example animations) create the appearance that user interface graphics behave in accordance with the …

程序员,当你写程序写累了怎么办。

记得泡泡网的CEO李想说过这样一句话&#xff0c;大体就是&#xff1a;做一件事情&#xff0c;一开始是兴趣使然&#xff0c;然而当三分钟热度过去之后&#xff0c;就要靠毅力支撑自己来完成它。至少我到现在是能非常深刻的体会这句话。一开始再怎么喜欢做一件事&#xff0c;要想…

mysql 导致iis 假死_解决IIS无响应假死状态

1 查看服务器iis的w3wp.exe对应的应用程序池在IIS6下&#xff0c;经常出现w3wp的内存占用不能及时释放&#xff0c;从而导致服务器响应速度很慢。今天研究了一下&#xff0c;可以做以下配置&#xff1a;1、在IIS中对每个网站进行单独的应用程序池配置。即互相之间不影响。2、设…

Swift 5将强制执行内存独占访问

Swift 5将带来改进的Swift程序内存安全性&#xff0c;在程序的其他部分修改变量时&#xff0c;不允许通过其他变量名来访问这些变量。这个变更对现有应用程序的行为和Swift编译器本身都有重要影响。Swift 5将带来改进的Swift程序内存安全性&#xff0c;在程序的其他部分修改变量…

GitHub 支持上传视频文件啦!

大家好&#xff0c;我是若川。今天周六&#xff0c;分享一篇热点新闻。文章较短&#xff0c;预计5分钟可看完。近日 Github 宣布支持了视频上传功能&#xff0c;意味着&#xff0c;大家在提 issue 时可以携带视频了&#xff0c;这极大地提高了开发者和维护者的效率&#xff0c;…

ui设计 网络错误_UI设计人员常犯的10个错误

ui设计 网络错误重点 (Top highlight)1.不考虑范围 (1. Disregarding scope)It’s not uncommon for designers to introduce features that will overcomplicate the development process while bringing no additional value to the application. Focusing on the business o…