C++常用命令

本文不对各个函数进行详细介绍,仅对本人在编程过程中使用的方法进行简单记录。

(1) string 字符串截取子串

//从Hello World!的下标为2的位置截取5个长度的字符串
string str = "Hello World!";
string str1 = str.substr(2,5);    //第一个参数是截取开始的下标,第二个参数是截取的位数
cout << str1 << endl;
return 0;

结果
llo W

(2)  string 按分隔符分割字符串(字符串流的使用)

#include <sstream>             //使用string流需要的头文件
#include <string.h>            //使用string类型需要的头文件

int main(){
	string text = "alice is a good girl she is a good student";
	istringstream iss(text);    //数据流出入的方式将text输入到iss中
	string str;
	while (iss >> str)         //按照分隔符一个单词一个单词的赋值给str
	{
		cout<<str<<'\t';
	}
	return 0;
}

//结果
alice	is	a	good	girl	she	is	a	good	student

(3)数组/容器数值求和/字符串连接

#include <iostream>
#include <vector>
#include <numeric>
using namespace std;

int main() {
	//数字求和
	vector<int> value(10, 2);	//声明并初始化一个容量为10,元素值为2的vector
	int sum = accumulate(value.begin() , value.end() , 0); 
	//前两个参数为要累加的元素范围,第三个则是累加的初值
	cout << sum << endl;
	
	vector<string> str_g(10,"a");	
	string str = accumulate(str_g.begin() , str_g.end() , string(" ")); 
	cout << str << endl;
	
	return 0;
}

结果
20
aaaaaaaaaa

(4)优先级队列

在优先队列中,元素被赋予优先级。当访问元素时,具有最高优先级的元素最先删除。优先队列具有最高级先出的行为特征。

#include <iostream>
#include <queue>                            //队列头文件
using namespace std;

int main() {
	priority_queue<int> temp_queue;        //定义一个优先队列
	for(int i = 1; i < 10;i++)
	{
		temp_queue.push(i);   //显示入队数据,队列遵循“先入先出”,但优先级队列遵循最大优先级先出
		cout <<temp_queue.top()<<'\t';
	}
	cout<<endl;
	for(int i = 1; i < 10;i++)
	{	                     //显示出队数据
		cout <<temp_queue.top()<<'\t';
		temp_queue.pop();
	}
	return 0;
}

结果
1	2	3	4	5	6	7	8	9	
9	8	7	6	5	4	3	2	1
发布了71 篇原创文章 · 获赞 38 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/u012839256/article/details/105080044