STL及一些常用函数的基本用法

1.vector(向量)的基本用法

vector是C++的STL中一个常见的容器,使用时需要加上#include\的头文件,其可以动态储存数据,既可以很方便的实现插入,删除等基本操作,其基本语法如下:

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int main()
  4. {
  5. vector<int> a;
  6. for(int i=0;i<10;i++)
  7. a.push_back(i); //push_back can add data in the end of vector
  8. int len=a.size(); //a.size() can return the length of vector,a.begin() return the first data's address,and a.end() is return last.
  9. cout<<len<<endl;
  10. a.insert(a.begin()+len,10); //insert a data in the len-th
  11. a.erase(a.end()); //delete a end data of vector
  12. a.pop_back(); //pop the last data
  13. if(a.empty()) //judge whether this vector is empty
  14. cout<<"The vector is empty!"<<endl;
  15. //a.reverse(a.begin(),a.end()); //reverse all the data.
  16. sort(a.begin(),a.end()); //sort the data from begin to the end of vector,can also add cmp function
  17. vector<int>::iterator it;
  18. for(it=a.begin();it<=a.end();it++) cout<<*it<<" ";
  19. cout<<endl; //ergodic all the datas of vector
  20. /*you can also use this operation to ergodic the data of vector
  21. for(vector<int>::size_type i=0;i<=a.size();i++) cout<<a[i]<<" ";
  22. cout<<endl;
  23. */
  24. a.clear(); //clear all the datas of the vector
  25. return 0;
  26. }

2.queue(队列)的基本用法

队列是C++STL中一个常见的容器,其具有先进先出的特点,在使用时要加#include\的头文件,其基本语法如下:

  1. #include<iostream>
  2. #include<queue>
  3. using namespace std;
  4. int main()
  5. {
  6. queue<int> myqueue; //定义队列
  7. for(int i=1;i<=5;i++)
  8. myqueue.push(i); //将i压入队列的底部(末端)
  9. cout<<myqueue.size()<<endl; //返回queue的长度
  10. cout<<myqueue.front()<<endl; //返回队列的第一个元素(也就是最先进入队列的元素,不会删除这个元素)
  11. if(myqueue.empty()) //判断这个queue中是否有元素(队列是否为空)
  12. cout<<"The queue is empty!"<<endl;
  13. myqueue.pop(); //删除第一个元素
  14. cout<<myqueue.front()<<endl;
  15. cout<<myqueue.back()<<endl; //返回queue的最后一个元素并将它输出出来(不删除)
  16. return 0;
  17. }

3.stack(栈)的基本操作

栈也是C++的STL中一种常见的容器,其使用时要加头文件#include\,是一种先进后出或者说后进先出的容器,其基本语法如下:

  1. #include<iostream>
  2. #include<stack>
  3. using namespace std;
  4. int main()
  5. {
  6. stack<int> mystack;
  7. if(mystack.empty()) //判断这个stack是否为空,如果为空,则返回1
  8. cout<<"The stack is empty!"<<endl;
  9. for(int i=1;i<=5;i++)
  10. mystack.push(i); //将元素push入stack中
  11. cout<<mystack.size()<<endl; //返回这个栈的length
  12. cout<<mystack.top()<<endl; //输出栈顶元素(最后加入的元素,不删除元素)
  13. mystack.pop(); //弹出栈顶的元素(删除栈顶元素)
  14. while(!mystack.empty()) //逆序遍历栈,但是栈的元素全部被删除
  15. {
  16. cout<<mystack.top()<<" ";
  17. mystack.pop();
  18. }
  19. return 0;
  20. }

4.set(集合)的基本用法

set是C++STL标准模板库的一个常用模板,其可以对里面的元素自动按升序排序,并去掉重复元素。其内部原理是红黑树,其基本语法如下:

  1. #include<iostream>
  2. #include<set>
  3. using namespace std;
  4. int main()
  5. {
  6. set<int> myset; //初始化定义一个set
  7. myset.insert(3); //向set中插入元素,注意set中没有Push这一成员函数,只能insert
  8. myset.insert(6);
  9. myset.insert(1);
  10. myset.insert(10);
  11. myset.insert(8);
  12. myset.insert(3);
  13. cout<<myset.size()<<endl; //返回set的大小
  14. for(set<int>::iterator it=myset.begin();it!=myset.end();it++)
  15. cout<<*it<<" ";
  16. cout<<endl;
  17. set<int>::iterator it=myset.find(3); //查找元素,返回元素所在的迭代器
  18. cout<<*it<<endl; //要注意,虽然it是set的迭代器,但是并不支持it<myset.end()的写法
  19. myset.erase(myset.find(1)); //删除元素,注意里面的参数是迭代器
  20. myset.erase(3); //也可以把要删除的值直接做参数传入set的erase中
  21. myset.erase(it,myset.end()); //区间删除,从it迭代器到末尾的元素全部删除
  22. myset.clear(); //清空集合
  23. return 0;
  24. }

5.map(映射)的基本用法

Map是c++的一个标准容器,她提供了很好一对一的关系,在一些程序中建立一个map可以起到事半功倍的效果,使用时需包含头文件#include<map>下面是map的一些基本操作:

  1. #include<iostream>
  2. #include<utility>
  3. #include<map>
  4. #include<string>
  5. using namespace std;
  6. int main()
  7. {
  8. map<string,int> mymap,map1,map2; //定义map变量
  9. map<string,int>::iterator it; //map的迭代器
  10. //向map变量中添加元素
  11. mymap.insert(pair<string,int>("a",1));
  12. mymap.insert(pair<string,int>("c",3));
  13. mymap.insert(pair<string,int>("b",2));
  14. mymap.insert(pair<string,int>("d",4));
  15. mymap.insert(pair<string,int>("e",5));
  16. mymap.insert(pair<string,int>("f",6));
  17. mymap["g"]=7;
  18. //map的查找,注意,我们通过map的键查找
  19. it=mymap.find("g");
  20. if(it==mymap.end()) cout<<"We haven't find the key!"<<endl;
  21. else
  22. cout<<it->first<<" "<<it->second<<endl; //键对应first,值对应second
  23. //map元素的删除
  24. it=mymap.find("d");
  25. if(it==mymap.end())
  26. cout<<"We haven't find the key!"<<endl;
  27. else
  28. mymap.erase(it); //删除迭代器,即删除这个元素
  29. //map的遍历
  30. map<string,int>::iterator it1;
  31. for(it1=mymap.begin();it1!=mymap.end();it1++)
  32. cout<<it1->first<<" "<<it1->second<<endl;
  33. //map的swap操作
  34. //注意,map中的swap不是一个元素之间的交换,而是map两个容器之间的交换
  35. map1.insert(pair<string,int>("be",1));
  36. map2.insert(pair<string,int>("af",2));
  37. map1.swap(map2);
  38. map<string,int>::iterator it2;
  39. for(it=map1.begin();it!=map1.end();it++)
  40. cout<<it->first<<" "<<it->second<<endl;
  41. //map的sort问题,map不能使用sort,因为map默认将插入的元素按照键的从小到大顺序排列
  42. cout<<mymap.size()<<endl; //返回map的迭代器数目
  43. /*
  44. 以下为map的一些常见子函数
  45. begin()          返回指向map头部的迭代器
  46.     clear()         删除所有元素
  47.     count()          返回指定元素出现的次数
  48.     empty()          如果map为空则返回true
  49.     end()            返回指向map末尾的迭代器
  50.     equal_range()    返回特殊条目的迭代器对
  51.     erase()          删除一个元素
  52. find()           查找一个元素
  53.     get_allocator()  返回map的配置器
  54.     insert()         插入元素
  55.     key_comp()       返回比较元素key的函数
  56.     lower_bound()    返回键值>=给定元素的第一个位置
  57.     max_size()       返回可以容纳的最大元素个数
  58.     rbegin()         返回一个指向map尾部的逆向迭代器
  59.     rend()           返回一个指向map头部的逆向迭代器
  60.     size()           返回map中元素的个数
  61.     swap()            交换两个map
  62.     upper_bound()     返回键值>给定元素的第一个位置
  63.     value_comp()      返回比较元素value的函数*/
  64. return 0;
  65. }

6.unorded_map的用法

unordered_map也是stl的容器之一,不过它与map的不同之处在于:unordered_map使用哈希的方式储存,所以其查找的效率能达到\(O(1)\)的效果,下面是其及基本用法:

  1. #include <unordered_map>
  2. #include <string>
  3. #include <iostream>
  4. using namespace std;
  5. unordered_map<string,double> m;
  6. int main() {
  7. m.insert(make_pair("PI", 3.14));
  8. m["root2"] = 1.414;
  9. m["root3"] = 1.732;
  10. m["log10"] = 2.302;
  11. m["loge"] = 1.0; //插入值
  12. m.insert(make_pair("e", 2.718));
  13. string key = "PI";
  14. if (m.find(key) == m.end()) //没找到
  15. cout << key << " not found\n\n";
  16. else cout << "Found " << key << "\n\n";
  17. //cout << m["Pi"] << endl; 是可行的
  18. unordered_map<string, double>::iterator it;
  19. for (it = m.begin(); it != m.end(); it++) //遍历元素
  20. cout << it->first << " " << it->second << endl;
  21. system("pause");
  22. return 0;
  23. }

7.list(列表)的基本用法

list是一种序列式容器。list容器完成的功能实际上和数据结构中的双向链表是极其相似的,list中的数据元素是通过链表指针串连成逻辑意义上的线性表,也就是list也具有链表的主要优点,即:在链表的任一位置进行元素的插入、删除操作都是快速的。在使用list时需加头文件#include,其基本语法如下:

  1. #include<iostream>
  2. #include<list>
  3. using namespace std;
  4. int main()
  5. {
  6. list<int> mylist,mylist2;
  7. for(int i=1; i<=5; i++)
  8. mylist.push_back(i); //尾插法
  9. mylist.push_front(0); //头插法
  10. if(mylist.empty())
  11. cout<<"The list is empty!"<<endl;
  12. cout<<mylist.size()<<endl;
  13. mylist.insert(mylist.end(),6); //插入元素
  14. mylist2.insert(mylist2.begin(),10);
  15. mylist.erase(mylist.begin()); //删除某一个元素
  16. //mylist.erase(mylist.begin(),mylist.end()); 删除某一个区间的元素
  17. list<int>::iterator it; //list的迭代器
  18. cout<<"Before swap:"<<endl;
  19. for(it=mylist.begin(); it!=mylist.end(); it++)
  20. cout<<*it<<" "; //list的遍历
  21. cout<<endl;
  22. mylist.pop_front(); //删除第一个list元素,pop_back(),删除最后一个元素
  23. mylist.resize(7); //重新设置list的最大长度,超出范围的将会被删除
  24. mylist.swap(mylist2);
  25. cout<<"After swap:"<<endl;
  26. for(it=mylist.begin();it!=mylist.end();it++)
  27. cout<<*it<<" ";
  28. cout<<endl;
  29. mylist.merge(mylist2); //将mylist2归并到mylist中去
  30. cout<<"After merge:"<<endl;
  31. for(it=mylist.begin();it!=mylist.end();it++)
  32. cout<<*it<<" ";
  33. cout<<endl;
  34. return 0;
  35. }

7.next_premutation(全排列)的用法

next_permutation可以方便快捷的实现全排列

  1. arr[5]={0,1,2,3,4};
  2. sort(arr,arr+5);
  3. do{
  4. for(int i=0;i<5;++i)
  5. cout<<arr[i]<<' ';
  6. cout<<endl;
  7. }while(next_permutation(arr,arr+5));
  8. //注意,该库函数是按照字典序的顺序完成全排列的

8.stringstream的用法

stringstream可以对getline很好的进行分离:

  1. string s,word;
  2. getline(cin,s);
  3. stringstream str(s);
  4. while(str>>word)
  5. cout<<word<<endl;

9.unique的用法

unique可以用来去重,该函数返回容器中不同元素的个数

  1. //以下标为1开始的数组为例
  2. int tot=unique(arr+1,arr+n+1)-(arr+1); //n为总元素个数
  3. int tot=unique(vec.begin(),vec.end())-vec.begin(); //计算vector不同元素数量

10.lower_bound的用法

该函数可以计算指定位置第一个大于等于传入参数的元素的下标,前提是数组单调(如果还要求不重复的话可先用unique去个重,再sort一下就好了)

  1. int pos=lower_bound(a+1,a+n+1,x)-a; //数组下标从1开始
  2. //在vector中也是类似
  3. int val=*--upper_bound(vec.begin(),vec.end(),x); //返回第一个大于等于x的数值(假设一定存在)

11.string中的substr的用法

截取一个子字符串

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int main()
  4. {
  5. string x="Hello_World";
  6. cout<<x.substr()<<endl; //cout<<"Hello_World"<<endl;
  7. cout<<x.substr(5)<<endl; //截取x[5]到结尾,cout<<"_world"<<endl;
  8. cout<<x.substr(0,5)<<endl; //以x[0]为始,向后截取5位(包含x[0])cout<<"Hello"<<endl;
  9. /*指定的截取长度加起始位置即_off+_count>源字符串的长度,则子字符串将延续到源字符串的结尾*/
  10. system("pause");
  11. }

各种STL的基本用法的更多相关文章

  1. C++中的STL中map用法详解(转)

    原文地址: https://www.cnblogs.com/fnlingnzb-learner/p/5833051.html C++中的STL中map用法详解   Map是STL的一个关联容器,它提供 ...

  2. STL的其他用法(adjacent_find, find_first_of, sort_heap, merge, binary_search)总结

    2017-08-20 17:26:07 writer:pprp 1.adjacent_find() 下面是源码实现: template <class ForwardIterator> Fo ...

  3. C++-STL:vector用法总结

    目录 简介 用法 1. 头文件 2. vector的声明及初始化 3. vector基本操作 简介 vector,是同一类型的对象的集合,这一集合可看作可变大小的数组,是顺序容器的一种.相比于数组,应 ...

  4. STL中map用法

    Map是 STL的一个关联容器,它提供一对一(其中第一个可以称为关键字,每个关键字只能在map中出现一次,第二个可能称为该关键字的值)的数据处理能力,由于 这个特性,它完成有可能在我们处理一对一数据的 ...

  5. [STL] SET实用用法

    背景 今天考试深受平衡树之害,可以参见上一篇博客,想到了set却苦于实用的不熟练.同时QTY询问set的具体用法,所以写这篇博客,同时留作自用. 分类 参看了一下网上其他set博客,上来都是长篇大论概 ...

  6. C++中的STL中map用法详解

    Map是STL的一个关联容器,它提供一对一(其中第一个可以称为关键字,每个关键字只能在map中出现一次,第二个可能称为该关键字的值)的数据 处理能力,由于这个特性,它完成有可能在我们处理一对一数据的时 ...

  7. C++ STL sort()函数用法

    C++STL提供的在里的排序函数,有以下两种形式 此外还提供有稳定排序版本stable_sort(),用法类似. 第一种形式: template <class RandomAccessItera ...

  8. (转载) STL中map用法详解

    Map是STL的一个关联容器,它提供一对一(其中第一个可以称为关键字,每个关键字只能在map中出现一次,第二个可能称为该关键字的值)的数据处理能力,由于这个特性,它完成有可能在我们处理一对一数据的时候 ...

  9. STL的常用用法、函数汇总(不定时更新)

    隶书文字为原创. 1.vector 在c++中,vector是一个十分有用的容器,下面对这个容器做一下总结. 1 基本操作 (1)头文件#include<vector>. (2)创建vec ...

  10. STL set 详细用法

    一个集合(set)是一个容器,它其中所包含的元素的值是唯一的. 用到的库 #include <set> 定义 最简单: set<int> a; set和其他的stl一样,都支持 ...

随机推荐

  1. IDEA导入Git项目后无Git选项

  2. Go 开发关键技术指南 | Go 面向失败编程 (内含超全知识大图)

    作者 | 杨成立(忘篱) 阿里巴巴高级技术专家 关注"阿里巴巴云原生"公众号,回复 Go 即可查看清晰知识大图! 导读:从问题本身出发,不局限于 Go 语言,探讨服务器中常常遇到的 ...

  3. 查看KVM宿主机上虚拟机的IP的脚本

    查看KVM宿主机上虚拟机的IP的脚本 #!/bin/bash #Auth:liucx #ping当前网段内在线的主机,以便产生arp记录. .{..};do { >& }& do ...

  4. 安装nodejs时提示Leaving directory

    在按照标准的编译命令./configure =>make =>make install 在make的时候发生错误: ../deps/v8/src/base/platform/mutex.h ...

  5. opencv:图像的算术操作

    前提:输入图像的大小和类型必须一致 越界处理: 大于255,则会减去255 小于0,则等于0 基本计算,加减乘除 #include <opencv2/opencv.hpp> #includ ...

  6. Abaqus-GUI开发-RSG

    目录 1. GUI开发简介 2. 目标和消息 2.1消息类型和消息ID 2.2消息映射 3. 控件创建 1. GUI开发简介 Abaqus GUI程序开发时,可以采用两种方式创建GUI图形界面. (1 ...

  7. 拿到别人的Django程序如何在本地RUN起来

    在Pycharm IDE下 Edit Configurations 1.检查Python interpreter 2.检查 Working directory 3.Settings 数据库配置

  8. java泛型demo

    1.泛型类 public class Dog<T> { private T age; public Dog(T age) { this.age = age; } public T getA ...

  9. django之反向解析和命名空间

    背景:当我们页面中存放的请求路径与url文件中的url一致时,如果url改了是不是所有的请求路径都要跟着改?显然不现实,这里我们就要用到反向解析. 如下图所示,输入url后会跳转到登录页面,输入用户名 ...

  10. python时间模块time,datetime

    时间模块time.datetime 模块(module)是 Python 中非常重要的东西,你可以把它理解为 Python 的扩展工具.换言之,Python 默认情况下提供了一些可用的东西,但是这些默 ...