各种STL的基本用法

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

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

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

#include<bits/stdc++.h>

using namespace std;

int main()
{
    vector<int> a;
    for(int i=0;i<10;i++)
        a.push_back(i);             //push_back can add data in the end of vector
    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.
    cout<<len<<endl;
    a.insert(a.begin()+len,10);     //insert a data in the len-th
    a.erase(a.end());               //delete a end data of vector
    a.pop_back();                   //pop the last data
    if(a.empty())                   //judge whether this vector is empty
        cout<<"The vector is empty!"<<endl;
    //a.reverse(a.begin(),a.end());   //reverse all the data.
    sort(a.begin(),a.end());        //sort the data from begin to the end of vector,can also add cmp function
    vector<int>::iterator it;
    for(it=a.begin();it<=a.end();it++)	cout<<*it<<" ";
    cout<<endl;                     //ergodic all the datas of vector
    /*you can also use this operation to ergodic the data of vector
    for(vector<int>::size_type i=0;i<=a.size();i++)	cout<<a[i]<<" ";
    cout<<endl;
    */
    a.clear();                      //clear all the datas of the vector
    return 0;
}

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

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

#include<iostream>
#include<queue>

using namespace std;

int main()
{
    queue<int> myqueue;             //定义队列
    for(int i=1;i<=5;i++)
        myqueue.push(i);            //将i压入队列的底部(末端)
    cout<<myqueue.size()<<endl;     //返回queue的长度
    cout<<myqueue.front()<<endl;    //返回队列的第一个元素(也就是最先进入队列的元素,不会删除这个元素)
    if(myqueue.empty())             //判断这个queue中是否有元素(队列是否为空)
        cout<<"The queue is empty!"<<endl;
    myqueue.pop();                  //删除第一个元素
    cout<<myqueue.front()<<endl;
    cout<<myqueue.back()<<endl;     //返回queue的最后一个元素并将它输出出来(不删除)
    return 0;
}

3.stack(栈)的基本操作

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

#include<iostream>
#include<stack>

using namespace std;

int main()
{
    stack<int> mystack;
    if(mystack.empty())               //判断这个stack是否为空,如果为空,则返回1
        cout<<"The stack is empty!"<<endl;
    for(int i=1;i<=5;i++)
        mystack.push(i);             //将元素push入stack中
    cout<<mystack.size()<<endl;      //返回这个栈的length
    cout<<mystack.top()<<endl;       //输出栈顶元素(最后加入的元素,不删除元素)
    mystack.pop();                   //弹出栈顶的元素(删除栈顶元素)
    while(!mystack.empty())          //逆序遍历栈,但是栈的元素全部被删除
    {
        cout<<mystack.top()<<" ";
        mystack.pop();
    }
    return 0;

}

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

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

#include<iostream>
#include<set>

using namespace std;

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

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

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

#include<iostream>
#include<utility>
#include<map>
#include<string>

using namespace std;

int main()
{
    map<string,int> mymap,map1,map2;                    //定义map变量
    map<string,int>::iterator it;             //map的迭代器
    //向map变量中添加元素
    mymap.insert(pair<string,int>("a",1));
    mymap.insert(pair<string,int>("c",3));
    mymap.insert(pair<string,int>("b",2));
    mymap.insert(pair<string,int>("d",4));
    mymap.insert(pair<string,int>("e",5));
    mymap.insert(pair<string,int>("f",6));
    mymap["g"]=7;
    //map的查找,注意,我们通过map的键查找
    it=mymap.find("g");
    if(it==mymap.end())		cout<<"We haven't find the key!"<<endl;
    else
        cout<<it->first<<" "<<it->second<<endl;  //键对应first,值对应second
    //map元素的删除
    it=mymap.find("d");
    if(it==mymap.end())
        cout<<"We haven't find the key!"<<endl;
    else
        mymap.erase(it);                        //删除迭代器,即删除这个元素
    //map的遍历
    map<string,int>::iterator it1;
    for(it1=mymap.begin();it1!=mymap.end();it1++)
        cout<<it1->first<<" "<<it1->second<<endl;
    //map的swap操作
    //注意,map中的swap不是一个元素之间的交换,而是map两个容器之间的交换
    map1.insert(pair<string,int>("be",1));
    map2.insert(pair<string,int>("af",2));
    map1.swap(map2);
    map<string,int>::iterator it2;
    for(it=map1.begin();it!=map1.end();it++)
        cout<<it->first<<" "<<it->second<<endl;
    //map的sort问题,map不能使用sort,因为map默认将插入的元素按照键的从小到大顺序排列
    cout<<mymap.size()<<endl;               //返回map的迭代器数目
    /*
    以下为map的一些常见子函数
    begin()          返回指向map头部的迭代器
    clear()         删除所有元素
    count()          返回指定元素出现的次数
    empty()          如果map为空则返回true
    end()            返回指向map末尾的迭代器
    equal_range()    返回特殊条目的迭代器对
    erase()          删除一个元素
    find()           查找一个元素
    get_allocator()  返回map的配置器
    insert()         插入元素
    key_comp()       返回比较元素key的函数
    lower_bound()    返回键值>=给定元素的第一个位置
    max_size()       返回可以容纳的最大元素个数
    rbegin()         返回一个指向map尾部的逆向迭代器
    rend()           返回一个指向map头部的逆向迭代器
    size()           返回map中元素的个数
    swap()            交换两个map
    upper_bound()     返回键值>给定元素的第一个位置
    value_comp()      返回比较元素value的函数*/
    return 0;
}

6.unorded_map的用法

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

#include <unordered_map>
#include <string>
#include <iostream>

using namespace std;
unordered_map<string,double> m;

int main() {
	m.insert(make_pair("PI", 3.14));
	m["root2"] = 1.414;
	m["root3"] = 1.732;
	m["log10"] = 2.302;
	m["loge"] = 1.0;		//插入值
	m.insert(make_pair("e", 2.718));
	string key = "PI";

	if (m.find(key) == m.end())	//没找到
		cout << key << " not found

";
	else    cout << "Found " << key << "

";
	//cout << m["Pi"] << endl; 是可行的

	unordered_map<string, double>::iterator it;
	for (it = m.begin(); it != m.end(); it++)		//遍历元素
		cout << it->first << "  " << it->second << endl;
	system("pause");
	return 0;
}

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

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

#include<iostream>
#include<list>

using namespace std;

int main()
{
    list<int> mylist,mylist2;
    for(int i=1; i<=5; i++)
        mylist.push_back(i);            //尾插法
    mylist.push_front(0);               //头插法
    if(mylist.empty())
        cout<<"The list is empty!"<<endl;
    cout<<mylist.size()<<endl;
    mylist.insert(mylist.end(),6);      //插入元素
    mylist2.insert(mylist2.begin(),10);
    mylist.erase(mylist.begin());       //删除某一个元素
    //mylist.erase(mylist.begin(),mylist.end());  删除某一个区间的元素
    list<int>::iterator it;             //list的迭代器
    cout<<"Before swap:"<<endl;
    for(it=mylist.begin(); it!=mylist.end(); it++)
        cout<<*it<<" ";                 //list的遍历
    cout<<endl;
    mylist.pop_front();                 //删除第一个list元素,pop_back(),删除最后一个元素
    mylist.resize(7);                   //重新设置list的最大长度,超出范围的将会被删除
    mylist.swap(mylist2);
    cout<<"After swap:"<<endl;
    for(it=mylist.begin();it!=mylist.end();it++)
        cout<<*it<<" ";
    cout<<endl;
    mylist.merge(mylist2);   //将mylist2归并到mylist中去
    cout<<"After merge:"<<endl;
    for(it=mylist.begin();it!=mylist.end();it++)
        cout<<*it<<" ";
    cout<<endl;
    return 0;
}

7.next_premutation(全排列)的用法

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

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

8.stringstream的用法

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

string s,word;
getline(cin,s);
stringstream str(s);
while(str>>word)
    cout<<word<<endl;

9.unique的用法

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

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

10.lower_bound的用法

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

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

11.string中的substr的用法

截取一个子字符串

#include <bits/stdc++.h>
using namespace std;
int main()
{
    string x="Hello_World";
    cout<<x.substr()<<endl;         //cout<<"Hello_World"<<endl;
    cout<<x.substr(5)<<endl;        //截取x[5]到结尾,cout<<"_world"<<endl;
    cout<<x.substr(0,5)<<endl;      //以x[0]为始,向后截取5位(包含x[0])cout<<"Hello"<<endl;
    /*指定的截取长度加起始位置即_off+_count>源字符串的长度,则子字符串将延续到源字符串的结尾*/
   system("pause");
}
原文地址:https://www.cnblogs.com/StungYep/p/12251709.html