C++之STL库简单介绍

1. sort()     可以自己定义新的结构体数组排序,sort第三个参数可以设置为根据哪个值排序

	int a[] = {2,-1,3,6,4,9,5};
	int n = sizeof(a) / sizeof(int); 
	sort(a, a + n);
	for (int i = 0; i<n; i++)
	{
		cout <<a[i] << " ";

	}
	return 0;

2. string

string s = "46237879426";   // 排序
sort(s.begin(),s.end());
cout << s;
	string s = "46237879426";
	s.erase(s.begin());  //删除第一个
	cout << s << endl;
	s.erase(--s.end());  //删除最后一个
	cout << s << endl;
	string s = "46237879426";   
	s = s.substr(2, 3); //从第二个位置开始,取三个
	cout << s << endl; 
	string s = "46237879426";
	cout << s.length() << endl;  //长度

3. vector

	vector<int> v;  //空的  初始为0
	// vector<int> v(4,6);   //初始化4个6
	v.push_back(1);
	v.push_back(2);
	v.push_back(3);
	v.push_back(4);
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
	{
		cout << *it;
	}
	vector<int> v = {4,6,1,8,52,9,3};
	sort(v.begin(), v.end());    //排序,可以加第三个参数即顺序和逆序
	for(auto x : v)      //此处在vs2010中会报错,使用VS2015没问题
		cout << x;

4. stack()

	stack<int> s;  //push,pop,size,empty
	s.push(2);
	s.push(3);
	cout << s.size() << endl;
	cout << s.top() << endl;
	s.pop();
	cout << s.top() << endl;
	cout << s.empty() << endl;
	s.pop();
	cout << s.empty() << endl;  //空值返回为1

5.  queue

	queue<int> q;
	q.push(5);
	q.push(6);
	cout <<q.size() << q.front() << q.back() << endl;
	q.pop();
	cout <<q.size() << q.front() << q.back() << endl;

6. map

	map<int,int> m;   //有序
	m[6]=3;
	m[5]=6;
	m[4]=9;
	for (auto it=m.begin();it!=m.end();it++)
	{
		cout << it->first << " " << it->second << endl;
	}
	unordered_map<int,int> m;   //有序
	m[6]=3;
	m[5]=6;
	m[4]=9;
	for (auto it=m.begin();it!=m.end();it++)
	{
		cout << it->first << " " << it->second << endl;
	}

7. set

	set<int> s;
	s.insert(3);
	s.insert(1);
	s.insert(3);
	cout << s.size() << endl;
	for (auto it = s.begin();it!=s.end();it++)
	{
		cout << *it << " ";
	}
	unordered_set<int> s;   //无序
	s.insert(3);
	s.insert(1);
	s.insert(3);
	cout << s.size() << endl;
	for (auto it = s.begin();it!=s.end();it++)
	{
		cout << *it << " ";
	}

8. deque  双端队列

	deque<int> d;
	d.push_back(1);
	d.push_front(2);
	d.push_back(3);
	d.push_front(4);
	for (auto it = d.begin();it!=d.end();it++)
	{
		cout << *it << " ";
	}

 

 

 

 

 

发布了10 篇原创文章 · 获赞 3 · 访问量 517
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览