STL 常用算法

1.      STL 常用算法

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;

}

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;       

}

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中的keyvalue分别存放在一个pair类型的vector中,然后利用vectorsort函数排序,其中map_verb存放我的map

2.       再新建一个map结构,然后把已知的map值得keyvalue分别作为新mapvaluekey,这样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

 

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

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;

}

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"

 

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}

 

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.      各种容器运用时机

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

²  vector与deque的比较:

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

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

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

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

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

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值