STL 常用算法

1.      STL 常用算法

l  for_each()

例1

//普通函数

voidFuncShowElemt2(int &t)

{

cout << t << " ";

}

vector<int> v1;

v1.push_back(1);

v1.push_back(3);

v1.push_back(5);

//通过回调函数  谁使用for_each 谁去填写回调函数的入口地址

for_each(v1.begin(), v1.end(), FuncShowElemt2);

例2

typedef
struct_Mystruct

{

inta;

intb;

}Mystruct;

void CallMyMethod(std::pair<const
int,Mystruct>& pair)

{

cout<<pair.first<<endl;

cout<<pair.second.a<<endl;

cout<<pair.second.b<<endl;

}

int main()

{

map<int,Mystruct>mapTest;

for_each(Map.begin(), Map.end(),CallMyMethod);

return0;

}

l  find_if

例1

bool IsOdd (int i) {

return((i%2)==1);

}

int main () {

std::vector<int> myvector;

myvector.push_back(10);

myvector.push_back(25);

myvector.push_back(40);

myvector.push_back(55);

std::vector<int>::iterator it = std::find_if (myvector.begin(),myvector.end(), IsOdd);

std::cout<< "The first odd value is " << *it << ‘\n‘;

return 0;

}

例2

#include <string>

#include <algorithm>

class map_value_finder

{

public:

map_value_finder(const std::string&cmp_string):m_s_cmp_string(cmp_string){}

booloperator ()(const std::map<int, std::string>::value_type &pair)

{

returnpair.second == m_s_cmp_string;

}

private:

conststd::string &m_s_cmp_string;

};

int main()

{

std::map<int, std::string> my_map;

my_map.insert(std::make_pair(10, "china"));

my_map.insert(std::make_pair(20, "usa"));

my_map.insert(std::make_pair(30, "english"));

my_map.insert(std::make_pair(40,"hongkong"));

std::map<int, std::string>::iterator it = my_map.end();

it =std::find_if(my_map.begin(), my_map.end(),map_value_finder("English"));

if (it ==my_map.end())

printf("not found\n");

else

printf("found key:%d value:%s\n", it->first,it->second.c_str());

return 0;

}

l  sort

例1.

bool Compare(const
int &a, const
int &b)

{

returna < b;
//从小到大

}

//普通函数

void printElement(int &t)

{

cout << t << " ";

}

void testSort()

{

vector<int> v1(10);

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

{

inttmp = rand() %100;

v1[i] = tmp;

}

for(vector<int>::iterator it=v1.begin();it!=v1.end(); it++ )

{

cout << *it <<" ";

}

cout << endl;

for_each(v1.begin(), v1.end(), printElement);

cout << endl;

sort(v1.begin(), v1.end(),Compare);

for_each(v1.begin(), v1.end(),printElement);

cout << endl;

}

例2

1.      将map中的key和value分别存放在一个pair类型的vector中,然后利用vector的sort函数排序,其中map_verb存放我的map值

2.       再新建一个map结构,然后把已知的map值得key和value分别作为新map的value和key,这样map结构就会自动按照value值排序啦~~


Transform

例1

//二元函数对象

template <typename T>

class SumAdd

{

public:

T operator()(Tt1, T t2)

{

return t1 +t2;

}

};

//v1 v2 ==>v3

vector<int>v1, v2;

vector<int>v3;

v1.push_back(1);

v1.push_back(3);

v1.push_back(5);

v2.push_back(2);

v2.push_back(4);

v2.push_back(6);

v3.resize(10);

transform(v1.begin(), v1.end(), v2.begin(), v3.begin(),SumAdd<int>() );

for(vector<int>::iterator it=v3.begin(); it!=v3.end(); it++ )

{

cout<< *it << " ";

}

cout <<endl;

例2:

l  Find

例1

int main () {

// usingstd::find with array and pointer:

int myints[] = {10, 20, 30, 40 };

int * p;

p = std::find(myints, myints+4, 30);

if (p !=myints+4)

std::cout<< "Element found in myints: " << *p << ‘\n‘;

else

std::cout<< "Element not found in myints\n";

// usingstd::find with vector and iterator:

std::vector<int> myvector (myints,myints+4);

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

it = find(myvector.begin(), myvector.end(), 30);

if (it !=myvector.end())

std::cout<< "Element found in myvector: " << *it << ‘\n‘;

else

std::cout<< "Element not found in myvector\n";

return 0;

}

例2

l  adjacent_find

在iterator对标识元素范围内,查找一对相邻重复元素,找到则返回指向这对元素的第一个元素的迭代器。否则返回past-the-end。

bool myfunction (int i, int j) {

return (i==j);

}

int main () {

int myints[] ={5,20,5,30,30,20,10,10,20};

std::vector<int> myvector (myints,myints+8);

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

// using defaultcomparison:

it =std::adjacent_find (myvector.begin(), myvector.end());

if(it!=myvector.end())

std::cout<< "the first pair of repeated elements are: " << *it<< ‘\n‘;

//using predicatecomparison:

it =std::adjacent_find (++it, myvector.end(), myfunction);

if(it!=myvector.end())

std::cout<< "the second pair of repeated elements are: " << *it<< ‘\n‘;

return 0;

}

l  random_shuffle

对指定范围内的元素随机调整次序。

例1

vector<int> vecInt;

vecInt.push_back(1);

vecInt.push_back(3);

vecInt.push_back(5);

vecInt.push_back(7);

vecInt.push_back(9);

stringstr("itcastitcast ");

random_shuffle(vecInt.begin(),vecInt.end());   //随机排序,结果比如:9,7,1,5,3

random_shuffle(str.begin(),str.end());                //随机排序,结果比如:" itstcasticat"

l  reverse

例1

vector<int> vecInt;

vecInt.push_back(1);

vecInt.push_back(3);

vecInt.push_back(5);

vecInt.push_back(7);

vecInt.push_back(9);

reverse(vecInt.begin(),vecInt.end());               //{9,7,5,3,1}

l  fill

将输入值赋给标志范围内的所有元素。

vector<int>vecIntA;

vecIntA.push_back(1);

vecIntA.push_back(3);

vecIntA.push_back(5);

vecIntA.push_back(7);

vecIntA.push_back(9);

fill(vecIntA.begin(),vecIntA.end(), 8);               //8, 8,8, 8, 8

2. #include
<functional>

Bind()

typedef struct _Mystruct

{

voidadd1(int a)

{

cout<<a<<endl;

}

voidadd2(int a,int b)

{

cout<<a<<"  "<<b<<endl;

}

}Mystruct;

void testbind(int a,int b)

{

cout<<a<<""<<b<<endl;

}

Int main()

{

using namespace std::placeholders;    // adds visibility of _1, _2, _3,...

auto test=bind(testbind,_1,_2);

test(10,15);

Mystruct testt;

autotestfun=bind(&Mystruct::add1,&testt,_1);

}

3. #include
<numeric>

例如:

vector<int> vecIntA;

vecIntA.push_back(1);

vecIntA.push_back(3);

vecIntA.push_back(5);

vecIntA.push_back(7);

vecIntA.push_back(9);

intiSum = accumulate(vecIntA.begin(), vecIntA.end(), 100);          //iSum==125

4.

5.      各种容器运用时机

2    deque的使用场景:比如排队购票系统,对排队者的存储可以采用deque,支持头端的快速移除,尾端的快速添加。如果采用vector,则头端移除时,会移动大量的数据,速度慢。

2  vector与deque的比较:

2  一:vector.at()比deque.at()效率高,比如vector.at(0)是固定的,deque的开始位置却是不固定的。

2  二:如果有大量释放操作的话,vector花的时间更少,这跟二者的内部实现有关。

2  三:deque支持头部的快速插入与快速移除,这是deque的优点。

2  list的使用场景:比如公交车乘客的存储,随时可能有乘客下车,支持频繁的不确实位置元素的移除插入。

2  set的使用场景:比如对手机游戏的个人得分记录的存储,存储要求从高分到低分的顺序排列。

2  map的使用场景:比如按ID号存储十万个用户,想要快速要通过ID查找对应的用户。二叉树的查找效率,这时就体现出来了。如果是vector容器,最坏的情况下可能要遍历完整个容器才能找到该用户。

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-07-29 07:44:54

STL 常用算法的相关文章

[C++ STL] 常用算法总结

1 概述 STL算法部分主要由头文件<algorithm>,<numeric>,<functional>组成.要使用 STL中的算法函数必须包含头文件<algorithm>,对于数值算法须包含<numeric>,<functional>中则定义了一些模板类,用来声明函数对象. 2 常用算法介绍 STL中算法大致分为四类: 非可变序列算法:指不直接修改其所操作的容器内容的算法. 可变序列算法:指可以修改它们所操作的容器内容的算法. 排序

C++ - STL常用算法-sort、find、count、等等【还有remove......暂时不写】

起始算法有很多,或者说太多,这里不写了,主要写一写在 vector deque stack queue set map 中出现过的算法,其他算法,以后在此补充! 这些算法使用时候,包含:#include<algorithm> 其余算法参考:https://blog.csdn.net/tick_tock97/article/details/71316372 在线手册:http://www.cplusplus.com/reference/algorithm 一.sort 没有返回值: 1 std:

c++ STL常用算法使用方法

#include <string> #include <vector> #include <functional> #include <iostream> using namespace std; void print(vector<int>& list, const string &des) { cout<<"after "<<des.c_str()<<", th

STL常用算法

1.copy()函数 int myints[]={10,20,30,40,50,60,70}; std::vector<int> myvector (7); std::copy ( myints, myints+7, myvector.begin() ); 将一个容器中的元素复制到另一个容器中 2.count()函数 int myints[] = {10,20,30,30,20,10,10,20};   // 8 elements int mycount = std::count (myint

STL常用算法总结 by StoneXie

include<algorithm> 1 sort(起始地址,结束地址+1,比较函数)作用:对连续存储的元素从起始地址到结束地址从小到大排序情况1:从大到小排序定义比较函数例子: bool cmp(int a,int b) { return(a>b); } 情况2:结构体数组排序法1:重载运算符(定义在结构体内部) struct Edge{ int no,w;//按w从小到大,w相同时按no从小到大 bool friend operator <(Edge a,Edge b) { i

STL中的常用算法

C++STL 常用算法,使用时包含#include <algorithm> 一.非变异算法 是一组不破坏操作数据的模板函数,用来对序列数据进行逐个处理.元素查找.子序列搜索.统计和匹配.非变异算法具有极为广泛的适用性,基本上可应用与各种容器. 1查找容器元素find 它用于查找等于某值的元素.它在迭代器区间[first,last)(闭开区间)上查找等于value值的元素,如果迭代器i所指的元素满足*i=value,则返回迭代器i:未找到满足条件的元素,返回last.函数原型:find( v1.

C++ STL 常用遍历算法

C++ STL 常用遍历算法 STL的容器算法迭代器的设计理念 1) STL的容器通过类模板技术,实现数据类型和容器模型的分离 2) STL的迭代器技术实现了遍历容器的统一方法:也为STL的算法提供了统一性奠定了基 础 3) STL的算法,通过函数对象实现了自定义数据类型的算法运算:所以说:STL的算法也提 供了统一性.                核心思想:其实函数对象本质就是回调函数,回调函数的思想:就是任务的编写者和任务的调用者有效解耦合.函数指针做函数参数.4) 具体例子:transf

C++ STL 常用算术和生成算法

C++ STL 常用算术和生成算法 accumulate() accumulate: 对指定范围内的元素求和,然后结果再加上一个由val指定的初始值. #include<numeric> vector<int> vecIntA; vecIntA.push_back(1); vecIntA.push_back(3); vecIntA.push_back(5); vecIntA.push_back(7); vecIntA.push_back(9); int iSum = accumul

STL——配接器、常用算法使用

学习STL,必然会用到它里面的适配器和一些常用的算法.它们都是STL中的重要组成部分. 适配器 在STL里可以用一些容器适配得到适配器.例如其中的stack和queue就是由双端队列deque容器适配而来.其实适配器也是一种设计模式,该种模式是将一个类的接口转换成用户希望的另外一个接口.简单的说:就是需要的东西就在眼前,但却不能用或者使用不是很方便,而短时间又无法改造它,那我们就通过已存在的东西去适配它. STL中的适配器一共有三种: ①应用于容器的即容器适配器:比如stack和queue就是对