STL中string的构造,遍历,抛异常

#include  <iostream>
using namespace std;
#include <string>

void main1()//string的构造函数
{
	string s1 = "aaaaa";
	string s2 = s1;//通过拷贝构造函数来初始化s2
	string s3("bbbbb");
	string s4(10,'a');//带参数的构造函数
	string s5;//默认构造函数
	cout << s1 << endl;
	cout << s2 << endl;
	cout << s3<< endl;
	cout << s4 << endl;

}


void main2()//数组方式遍历
{
	string s1 = "abcdef";
	for (int i = 0; i < s1.length(); i++)
	{
		cout<< s1[i] <<" ";
	}
	cout << endl;
}


void main3()//迭代器方式遍历
{
	string s1 = "abcdef";
	for (string::iterator it = s1.begin(); it != s1.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
}


void main4()//at()方式抛异常
{
	string s1 = "abcdef";
	try
	{
		for (int i = 0; i < s1.length() + 3; i++)
		{
			cout << s1.at(i) << " ";
		}
	}
	catch (...)
	{
		cout << "发生了异常" << endl;
	}
}


void main5()//数组方式方式抛异常
{
	string s1 = "abcdef";
	try
	{
		for (int i = 0; i < s1.length() + 3; i++)
		{
			cout << s1[i] << " ";
		}
	}
	catch (...)
	{
		cout << "发生了异常" << endl;
	}
}


int main()
{
	main1();
	main2();
	main3();
	main4();
	//main5();
	return 0;
}


上面代码执行结果如下图:

构造方法有几种:(1)默认构造函数 (2)拷贝构造函数 (4)带参数的构造函数


抛异常的时候,用at()方法,用数组方式抛异常的话会发生中断,数组越界,发生错误。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值