admin管理员组文章数量:1794759
【C++/STL】string的使用及底层剖析
1、string 对象类的常见构造
(constructor)函数名称 功能说明: string() (重点) 构造空的string类对象,即空字符串 string(const char* s) (重点) 用C-string来构造string类对象 string(size_t n, char c) string类对象中包含n个字符c string(const string&s) (重点) 拷贝构造函数
代码语言:javascript代码运行次数:0运行复制void test_string1() {
//常用
string s1; //定义
string s2("hello world"); //拷贝构造
string s3(s2);
//不常用 了解
//从s2的第三个字符开始拷贝,拷贝5个字符,如果5大于后面的字符数,到'\0'停止
string s4(s2, 3, 5);
string s5(s2, 3); //从s2的第三个字符开始拷贝
string s6(s2, 3, 30);
string s7("hello world", 5);
string s8(10, 'x');
cout << "s1 = " << s1 << endl;
cout << "s2 = " << s2 << endl;
cout << "s3 = " << s3 << endl;
cout << "s4 = " << s4 << endl;
cout << "s5 = " << s5 << endl;
cout << "s6 = " << s6 << endl;
cout << "s7 = " << s7 << endl;
cout << "s8 = " << s8 << endl;
}
2、string的隐式类型转换和构造
void test_string2()
{
string s1("hello world"); //构造
string s2 = "hello world"; //隐式类型转换
const string& s3 = "hello world";// 临时对象具有常性,加const
}
3、string类对象的容量操作
代码语言:javascript代码运行次数:0运行复制void test_string3()
{
string s1("hello world");
cout << s1.size() << endl;
//capacity 比 实际空间少一个,有一个多的是预留给\0
cout << s1.capacity() << endl;
cout << s1.max_size() << endl;
}
4、string的遍历
代码语言:javascript代码运行次数:0运行复制void test_string4() {
// 遍历方式:下标 + []
string s1 = "hello world";
for (int i = 0; s1[i]; i++)
{
cout << s1[i] << " ";
}
cout << endl;
//遍历方式2:迭代器
string::iterator it1 = s1.begin();
while (it1 != s1.end()) {
cout << *it1 << " ";
++it1;
}
cout << endl;
cout << typeid(it1).name() << endl;
//遍历方式3:范围for
// 底层:就是迭代器
for (auto e : s1) {
cout << e << " ";
}
}
注意:迭代器中的begin和end
5、reverse逆置
代码语言:javascript代码运行次数:0运行复制void test_string5() //反向迭代器
{
string s1("hello world");
string::const_iterator it1 = s1.begin();
//auto it1 = s1.begin();
while (it1 != s1.end())
{
//*it1 += 3;// 不能修改
cout << *it1 << " ";
++it1;
}
string s2("hello world");
string::reverse_iterator it2 = s2.rbegin();
while (it2 != s2.rend()) {
*it2 += 3;
cout << *it2 << " ";
++it2;
}
}
6、const
7、sort排序
代码语言:javascript代码运行次数:0运行复制void test_string6()
{
string s1("hello world");
cout << s1 <<endl;
//按字典序排序
sort(s1.begin(), s1.end());
//第一个和最后一个参与排序
sort(++s1.begin(), --s1.end());
//前五个排序
sort(s1.begin(), s1.begin() + 5);
cout << s1 << endl;
}
8、插入删除
本文标签: CSTLstring的使用及底层剖析
版权声明:本文标题:【C++STL】string的使用及底层剖析 内容由林淑君副主任自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.xiehuijuan.com/baike/1754827267a1706972.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论