C++常用方法记录

map & set

  1. 迭代器

  2. 判断是否存在

  3. map按value排序
    sort()方法只能对线性结构对象进行排序,因此需要将map对象转换为vector<pair<typeA, typeB>>对象进行排序。

unordered_map<char, int> s_map;
...
vector<pair<char, int> > s_pairs(s_map.begin(), s_map.end());
sort(s_pairs.begin(), s_pairs.end(),
	[](const pari<char, int>& p1, const pair<char, int>& p2) {
		return p1.second > p2.second;
	});
  1. map按key排序

字符串分割

  1. 空格分割
    对于空格分割的字符串,可以使用istringstream对象进行分割,头文件为#include <sstream>
istringstream input(str);
string temp;
while(input >> temp){
    cout<<temp<<endl;
}

逐行读取文件,并对每行文字进行处理:

int main(int argc, char* argv[])
{
	std::string line;
	std::string word;
	std::ifstream fin("test.txt");
	
	while (getline(fin, line))
	{
		std::istringstream stream(line);
		while (stream >> word)
			std::cout << word << "\n";
	}
	getchar();
	return 0;
}
  1. 任意字符分割
    对于任意字符分割的字符串,可以使用istringstreamgetline()函数结合的方法。
    getline()函数原型为:istream& getline ( istream &is , string &str , char delim ),当遇到delim时停止读取,返回一个istream对象。
int main()
{
	string str;	
	string str_cin("one#two#three");
	stringstream ss;
	ss << str_cin;
	while (getline(ss, str, '#'))
		cout << str<< endl;
	system("pause");
	return 0;
}

字符串转换

使用stringstream进行字符串相关的类型转换。

  1. 字符串转为其他类型
#include <iostream>
#include <sstream>

using namespace std;

int main() {
    float a;
    stringstream sstream;
    sstream << "123.456";
    sstream >> a;
    cout << a << endl;
}
  1. 其他类型转为字符串类型
#include <iostream>
#include <sstream>

using namespace std;

int main() {
    float a = 123.456;
    string s;
    stringstream sstream;
    sstream << a;
    sstream >> s;
    cout << s << endl;
}
  1. 判断字符串是否为整型数字
    如果字符串不能转为整型,那么转换后的值为0。
bool isNum(const string& s) {
    stringstream sstream;
    sstream << s;
    int test;
    if (sstream >> test && sstream.eof())
        return true;
    return false;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值