【C++】STL--string(上)

前言

C语言中,字符串是以'\0'结尾的一些字符的集合,为了操作方便,C标准库中提供了一些str系列的库函数,但是这些库函数与字符串是分离开的,不太符合OOP的思想,而且底层空间需要用户自己管理,稍不留神可能还会越界访问。

在OJ中,有关字符串的题目基本以string类的形式出现,而且在常规工作中,为了简单、方便、 快捷,基本都使用string类,很少有人去使用C库中的字符串操作函数。

1.标准库中的string类

C++中的string类是STL中的一个重要的组成部分,string类是一个用于操作字符串的强大工具。

在使用string类时,必须包含#include头文件以及using namespace std;

下面是参考的官方链接

https://cplusplus.com/reference/string/string/?kw=string


2. string类对象的常见构造

#include <iostream>
using namespace std;
#include <string>
int main()
{
	string s1;// 构造空的string类对象s1
	string s2("hello world");// 用C格式字符串构造string类对象s2
	string s3(s2);// 拷贝构造s3

	cout << s1 << endl;
	cout << s2 << endl;
	cout << s3 << endl;

	string s7(10, 'x');//string类对象中包含n个字符c
	cout << s7 << endl;
}

3.string类对象的容量操作

void test_string5()
{

	string s2("hello world");
	cout << s2.length() << endl;//求长度,不包括/0
	cout << s2.size() << endl;//求长度,一般用size,不包括/0
	cout << s2.capacity() << endl;//求容量

	//清理有效字符
	s2.clear();

	string s("I love you");
	cout << s.length() << endl;//求长度
	cout << s.size() << endl;//求长度,一般用size,不包括/0

	//使用empty判空
	if (s.empty())
		cout << " empty" << endl;
	else
		cout << "not empty" << endl;
	s.resize(17, 'f'); //将有效字符的个数改成n个,多出的空间用字符c填充
	cout << s << endl;
	cout << s.length() << endl;
	cout << s.size() << endl;
	cout << s.capacity() << endl;
	
	
	//清理有效字符
	s.clear();
	//多打印几行看看
	cout << s << endl;
	cout << s << endl;
	cout << s << endl;
}

上面我们可以看到capacity会随着字符串增加而变化,那么扩容是怎么扩容的呢?如下

扩容在VS和g++中略显不同的,大家可以去尝试一下。

VS下

void TestPushBack()
{
	string s;
	//提前开空间,避免扩容,提高效率
	//s.reserve(100);
	size_t sz = s.capacity();
	cout << "capacity changen: " << sz << '\n';
	cout << "making s grow:\n";
	for (int i = 0; i < 100; i++)
	{
		s.push_back('c');
		if (sz != s.capacity())
		{
			sz = s.capacity();
			cout << "扩容: " << sz << '\n';
		}
	}
}

当把/0加上时发现第一次扩容是2倍扩,后面扩容是1.5倍扩,这是VS自己规定的变化规则,为什么第一次是2倍扩呢?当字符串小于16字节时会存放在一个固定的buff数组中,超过16会2倍扩容,后面开辟空间是在堆上。

g++

 可以看到g++扩容就是2倍扩

注意:

1. size()与length()方法底层实现原理完全相同,引入size()的原因是为了与其他容器的接口保持一致,一般情况下基本都是用size()。

2. clear()只是将string中有效字符清空,不改变底层空间大小。

3. resize(size_t n) 与 resize(size_t n, char c)都是将字符串中有效字符个数改变到n个,不同的是当字符个数增多时:resize(n)用0来填充多出的元素空间,resize(size_t n, char c)用字符c来填充多出的元素空间。注意:resize在改变元素个数时,如果是将元素个数增多,可能会改变底层容量的大小,如果是将元素个数减少,底层空间总大小不变。

4. reserve(size_t res_arg=0):为string预留空间,不改变有效元素个数,当reserve的参数小于string的底层空间总大小时,reserver不会改变容量大小。

void test_string4()
{
	string s2("hello worldxxxxxxxxxxxxx");
	cout << s2.size() << endl;
	cout << s2.capacity() << endl << endl;

	s2.reserve(20);
	cout << s2.size() << endl;
	cout << s2.capacity() << endl << endl;

	s2.reserve(28);
	cout << s2.size() << endl;
	cout << s2.capacity() << endl << endl;

	s2.reserve(40);
	cout << s2.size() << endl;
	cout << s2.capacity() << endl << endl;

	s2.reserve(80);
	cout << s2.size() << endl;
	cout << s2.capacity() << endl << endl;

	s2.reserve(10);
	cout << s2.size() << endl;
	cout << s2.capacity() << endl << endl;

	//s2.clear();
	//cout << s2.size() << endl;
	//cout << s2.capacity() << endl << endl;

}

4.auto和范围for

auto关键字

在这里补充2个C++11的小语法,方便我们后面的学习。

在早期C/C++中auto的含义是:使用auto修饰的变量,是具有自动存储器的局部变量,后来这个不重要了。C++11中,标准委员会变废为宝赋予了auto全新的含义即:auto不再是一个存储类型指示符,而是作为一个新的类型指示符来指示编译器,auto声明的变量必须由编译器在编译时期推导而得。

用auto声明指针类型时,用auto和auto*没有任何区别,但用auto声明引用类型时则必须加&

当在同一行声明多个变量时,这些变量必须是相同的类型,否则编译器将会报错,因为编译器实际 只对第一个类型进行推导,然后用推导出来的类型定义其他变量。

auto不能作为函数的参数,可以做返回值,但是建议谨慎使用

auto不能直接用来声明数组

int func1()
{
	return 10;
}

// 不能做参数
//void func0(auto a = 0)
//{}

auto func2()
{
	//...
	return func1();
}

auto func3()
{
	//...
	return func2();
}
int main()
{
	int a = 10;
	auto b = a;
	auto c = 'a';
	auto d = func1();
	// 编译报错:rror C3531: “e”: 类型包含“auto”的符号必须具有初始值设定项
	//auto e;
	cout << typeid(b).name() << endl;
	cout << typeid(c).name() << endl;
	cout << typeid(d).name() << endl;

    int x = 10;
    auto y = &x;
    auto* z = &x;
    auto& m = x;
    cout << typeid(x).name() << endl;
    cout << typeid(y).name() << endl;
    cout << typeid(z).name() << endl;
    cout << typeid(m).name() << endl;

	auto ret = func3();//这里使用auto复杂

	auto aa = 1, bb = 2;
	// 编译报错:error C3538: 在声明符列表中,“auto”必须始终推导为同一类型
	//auto cc = 3, dd = 4.0;

	// 编译报错:error C3318: “auto []”: 数组不能具有其中包含“auto”的元素类型
	auto array[] = { 1, 2, 3, 4, 5 };

	return 0;
}

#include<iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
	std::map<std::string, std::string> dict = { { "apple", "苹果" },{ "orange",
	"橙子" }, {"pear","梨"} };
	// auto的用武之地
	//std::map<std::string, std::string>::iterator it = dict.begin();
	auto it = dict.begin();
	while (it != dict.end())
	{
		cout << it->first << ":" << it->second << endl;
		++it;
	}
	return 0;
}

范围for

对于一个有范围的集合而言,由程序员来说明循环的范围是多余的,有时候还会容易犯错误。因此 C++11中引入了基于范围的for循环。for循环后的括号由冒号“ :”分为两部分:第一部分是范围内用于迭代的变量,第二部分则表示被迭代的范围,自动迭代,自动取数据,自动判断结束。

范围for可以作用到数组和容器对象上进行遍历

范围for的底层很简单,容器遍历实际就是替换为迭代器,这个从汇编层也可以看到。

#include<iostream>
#include <string>
using namespace std;
int main()
{
	int array[] = { 1, 2, 3, 4, 5 };
	// C++98的遍历
	for (int i = 0; i < sizeof(array) / sizeof(array[0]); ++i)
	{
		array[i] *= 2;
	}
	for (int i = 0; i < sizeof(array) / sizeof(array[0]); ++i)
	{
		cout << array[i] <<" ";
	}
	cout << endl;
	// C++11的遍历
	for (auto& e : array)
		e *= 2;
	for (auto e : array)
		cout << e << " ";
	cout << endl;

	string str("hello world");
	for (auto ch : str)
	{
		cout << ch << " ";
	}
	cout << endl;
	return 0;
}

5. string类对象的访问及遍历操作

void test_string8()
{
	string s2("hello world");
	cout<< s2[6] << endl;

	s2[0] = 'x';//修改下标为0的元素
	cout<< s2 << endl;

}

使用[]让我们访问元素和修改元素变得非常方便

begin、end、rbegin、rend的使用方法如下

#include<iostream>
#include <string>
using namespace std;
int main()
{
	string str1,str2;
	str1 = "hello world";
	//定义一个正向迭代器
	string::iterator ptr1 = str1.begin();
	//正向输入字符串
	while (ptr1 !=str1.end())
	{
		cout << *ptr1++ << " ";
	}
	cout << endl;

	str2 = "I love you";
	//定义一个反向迭代器
	string::reverse_iterator ptr2 = str2.rbegin();
	//逆向输出字符串
	while (ptr2 != str2.rend())
	{
		//逆向迭代器移动是反方向,所以从尾部来移动
		cout << *ptr2++<< " ";
	}
	cout << endl;
}

 

迭代器有四种 

//定义一个正向迭代器
string::iterator ptr1 = str1.begin();
//常对象正向迭代器
string::const_iterator ptr1 = str1.begin();
//定义一个反向迭代器
string::reverse_iterator ptr2 = str2.rbegin();
//常对象反向迭代器
string::const_reverse_iterator ptr2 = str2.rbegin();

C++11支持我们使用auto来定义迭代器,让编译器推到迭代器的类型

#include<iostream>
#include <string>
using namespace std;
void tets_string()
{
	string s1("hello world");//带参
	// 正向迭代器
	//string::iterator it = s1.begin();
	auto it = s1.begin();//auto自动推导
	while (it != s1.end())
	{
		cout << *it << " ";
		++it;
	}
	cout << endl;
	cout << s1 << endl;


	string s2("I love you");//带参
	// 反问迭代器
	//string::reverse_iterator rit = s2.rbegin();
	auto rit = s2.rbegin();//auto自动推导
	while (rit != s2.rend())
	{
		cout << *rit << " ";
		++rit;//移动到下一个字符
	}
	cout << endl;
	cout << s2 << endl;

}
int main()
{
	tets_string();
	return 0;
}

范围for

void test_string1()
{
	string s2("hello world");//带参

	//字符赋值,自动迭代,自动判断结束
	//底层就是迭代器
	// 范围for
	//for (auto ch : s2)
	for(auto& ch : s2)
	{
		cout << ch << " ";
	}
	cout << endl;
	cout << s2 << endl;
}

结束语

本节内容到此结束,下节我们继续扩展string的其他接口,敬请期待!

感谢大家的支持,如有不对的地方还请各位看客不吝指正

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值