栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

常用STL

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

常用STL

2022.05.14
      • vector
      • queue
      • map
      • bitset
      • pair

vector
#include 
#include 

using namespace std;

int main(){
	vector whq = {1, 2, 3};
	cout << whq[1] << endl; // 2  支持随机访问
	whq.push_back(4);
	cout << whq.size() << endl; // 1 2 3 4 共4个
	whq.pop_back();
	cout << whq.size() << endl; // 1 2 3 共3个
	
	cout << whq.empty() << endl; //false-> 0
	whq.clear();
	cout << whq.empty() << endl << endl; // true->1
	
	// vector遍历
	whq = {1, 2, 3};
	for (int i = 0; i < whq.size(); i ++)
        cout << whq[i] << endl; // 1 2 3
    // 采用迭代器
    for (vector::iterator it = whq.begin(); it != whq.end(); it ++)
        cout << *it << endl; // 1 2 3
	
	cout << whq.front() << endl; // 1
	cout << whq.back() << endl; // 3
	

	
	return 0;
}

定义二维vector, 如n*m的vector。
vector> a(n, vector(m));

vector> st(n, vector(m));

queue
#include 
#include  // 包括queue与priority_queue

using namespace std;

int main(){
	struct Rec{
		int a, b, c;
		bool operator> (const Rec& t) const {// 有sort则必须运算符重载,具体:小根堆重载>,大根堆重载<
			return a > t.a;
		}
	};
	
	queue q;
	q.push(1);
	q.pop();
	cout << q.front() << endl; // 0
	cout << q.back() << endl; // 1
	cout << "   " << endl;
	
	
	priority_queue a; // 默认为大根堆 
	// 小根堆
	priority_queue, greater> b; 
	// 此处为结构体小根堆,需要手动重载>;若为大根堆则重载< 
	priority_queue, greater> d; 
	d.push({3, 2}); // 3 < 100
	d.push({100, 2});
	
	cout << d.top().a << endl; // 3 查看堆顶元素
	cout << d.top().b << endl; // 2
	cout << d.top().c << endl; // 0 未赋值则默认为0
	
	cout << d.empty() << endl; // false->0
	cout << d.size() << endl; // 2
	cout << "   " << endl;
	
	priority_queue> e;
	e.push({10, 2});
	e.push({3, 2});
	cout << e.top().first << endl; // 10
	
	return 0;
}
map

内部实现为红黑树

#include 
#include 

using namespace std;

int main(){
		
	map> m;
	// 两种方法
	m.insert({"whq", vector()}); 
	
	m["whq"] = vector({1, 2, 3, 4, 5});
	
	cout << m["whq"][2] << endl; // 3
	cout << (m.find("whq") == m.end()) << endl << endl; // false->0
	
		
	return 0;
}
bitset
#include 
#include 

using namespace std;

int main(){
	bitset<1000> bb;
	bitset<1000> cc;
	bitset<1000> dd;
	bb[0] = 1;
	bb[2] = 1; // bb.set(2); reset则设为0
	cc[1] = 1;
	cout << (bb | cc).count() << endl; // 3 返回1的个数为3
	cout << bb[0] << " " << bb[1] << endl; // 1 0
	cout << bb.count() << endl; // 2
	cout << sizeof(bb) << endl; // 128
	
	return 0;
}

pair
#include 

using namespace std;

int main(){
	pair a;
	a = {2018, "whq"};
	cout << a.first << " " << a.second << endl; // 2018 whq
	
	a = make_pair(1, "hello");
	cout << a.first << ' ' << a.second << endl; // 1 hello
	
	return 0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/887066.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号