map & set
-
迭代器
-
判断是否存在
-
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;
});
- map按key排序
字符串分割
- 空格分割
对于空格分割的字符串,可以使用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;
}
- 任意字符分割
对于任意字符分割的字符串,可以使用istringstream与getline()函数结合的方法。
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进行字符串相关的类型转换。
- 字符串转为其他类型
#include <iostream>
#include <sstream>
using namespace std;
int main() {
float a;
stringstream sstream;
sstream << "123.456";
sstream >> a;
cout << a << endl;
}
- 其他类型转为字符串类型
#include <iostream>
#include <sstream>
using namespace std;
int main() {
float a = 123.456;
string s;
stringstream sstream;
sstream << a;
sstream >> s;
cout << s << endl;
}
- 判断字符串是否为整型数字
如果字符串不能转为整型,那么转换后的值为0。
bool isNum(const string& s) {
stringstream sstream;
sstream << s;
int test;
if (sstream >> test && sstream.eof())
return true;
return false;
}
1万+

被折叠的 条评论
为什么被折叠?



