【C++常用STL容器及方法汇总】

vector

#include   
#include

//初始化
vector data;
vector data(10,"hello");
vector data(5,(1,2,3,4,5));
vector> data;
//常用
data.size();
if(data.empty())
reverse(data.begin(),data.end());
------------------------------------------------------------------------------------------------------------
sort(data.begin(),data.end());  //升序
sort(data.begin(), data.begin()+3);  //部分升序
bool GreaterSort (Point2 a,Point2 b) { return (a.x>b.x); }
bool LessSort (Point2 a,Point2 b) { return (a.x vec{ 1, 2, 3, 4, 5 };
vector::iterator it = vec.begin() + 2;
vec.erase(it);    //删除迭代器指定元素;
//截取
vector v4(v1.begin(),v1.begin()+5); 

queue

#include
 
queue q;
q.size();
q.front();   //队列头元素
int num=q.top(); 
q.back();    //队列尾元素
q.push(2);
q.pop();
if(q.empty());
queueq2=q; //复制队列
queueq3(q); //复制队列
q=queue(); //设置为空队列
priority_queue
#include 

//定义
priority_queue pq;                          //默认大顶堆
priority_queue,less> pq1;    //大顶堆
priority_queue,greater> pq2;  //小顶堆

//常用方法
top()  :返回元素中第一个元素的引用
push():插入一个元素,并重新维护堆,无返回值.
pop() :删除优先级最高的元素,并重新维护堆无返回值
size() :返回容器中有效元素的数量,返回队列的大小
empty() :检测容器是否为空.返回“true”或者“false”.

stack

#include
 
stack s;
s.size();
if(s.empty());栈为空返回true
s.push("hello!");
s.pop();
string str=s.top();

stack s2=s; //复制栈
stacks3(s); //复制栈
s=stack(); //设置为空栈

map

#include
using namespace std;
 
map m; 
//赋值
m[0]="a";
m[1]="b";
m[2]="c";
//插入
pair value(3,"d");
m.insert(value);
//遍历
map::iterator it=m.begin();
for(;it!=m.end();it++)
    cout<first<<" "<second<second="abc";            //可改变value值,不可改key值
//查询
if(m.count())                //返回0或1
it=m.find(5);                //返回的是迭代器,查找key值
if(it=m.end())
    cout<<"NO Match";
//删除
m.erase(it);
m.erase(m.begin(),m.end());
m.erase("d");

set

#include
using namespace std;
 
//集合,自动排序
unordered_set s;
set s;
//插入
s.insert(2);
s.insert(5);
s.insert(3);
s.insert(6);
s.insert(1);
//遍历
set::iterator it;
for (it = s.begin(); it != s.end(); ++it)
	cout << *it << " ";
cout << endl;
//删除
s.erase(2);
for (it = s.begin(); it != s.end(); ++it)
	cout << *it << " ";
cout << endl;
//查找
if (s.find(6) == s.end() || s.count(5)) {
	cout << "No Match"<

输入输出

//输出
int x = 7;
printf("%03d", x); //007
printf("%02d", x); //07
printf("%3d", x); //空格空格7
printf("%d", x); //7
//转string后输出
int i = 10;   
cout<

string、char、int等相互转换

//int类型转换为char类型
	int num = 6;
	char c = num + '0';
	cout<

参考链接:
容器及方法
输入输出参考1
输入输出参考2
STL参考1
STL参考2
priority_queue_1
priority_queue_2
string with int_1
string with int_2

你可能感兴趣的:(c++,开发语言)