C++提高程式設計-STL

逆天峰發表於2024-11-23

STL初識

image
image
image
image
image

容器演算法迭代器初識

vector存放內建資料型別

#include<vector>
#include<algorithm>

void myPrint(int x)
{
	cout << x << ' ';
}

void test01()
{
	//建立vector容器
	vector<int>v;

	//向容器中插入資料
	v.push_back(10);
	v.push_back(20);
	v.push_back(30);
	v.push_back(40);

	//透過迭代器訪問資料
	for (vector<int>::iterator it = v.begin(); it < v.end(); it++)
	{
		cout << *it << endl;
	}

	//透過演算法訪問
	for_each(v.begin(), v.end(), myPrint);
}

vector存放自定義的資料型別

//vector存放自定義型別
class Person
{
public:

	Person(string name, int age)
	{
		this->m_Age = age;
		this->m_Name = name;
	}

	void showPerson()
	{
		cout << this->m_Name << ' ' << this->m_Age << endl;
	}

	string m_Name;
	int m_Age;
};

void myPrint(Person x)
{
	x.showPerson();
}

void test01()
{
	//建立vector容器
	vector<Person>v;

	//建立物件
	Person p1("aaa", 10);
	Person p2("bbb", 20);
	Person p3("ccc", 30);
	Person p4("ddd", 40);
	Person p5("eee", 50);

	//向容器中插入資料
	v.push_back(p1);
	v.push_back(p2);
	v.push_back(p3);
	v.push_back(p4);
	v.push_back(p5);

	//透過迭代器訪問資料
	for (vector<Person>::iterator it = v.begin(); it < v.end(); it++)
	{
		it->showPerson();
	}

	//透過演算法訪問
	for_each(v.begin(), v.end(), myPrint);
}

string容器

image

string的建構函式

image
示例程式碼

//1.預設構造
string s1;

//2.利用c語言的字串初始化
const char* str = "hello,word";
string s2(str);
cout << s2 << endl;

//3.複製構造
string s3(s2);
cout << s3 << endl;

//4.字元重複,初始化字串
string s4(10, 'a');
cout << s4 << endl;

string的賦值操作

image

void test01()
{
	const char* ch = "hello world";
	//1.將c語言的字串給string,以下兩者等價
	string st1;
	st1 = "hello world";
	st1 = ch;
	//2.把字串賦值
	string st2;
	st2 = st1;
	cout << st2 << endl;
	//3.將單個字元賦值
	string st3;
	st3 = 'a';
	cout << st3 << endl;
	//4.透過assign賦常量
	string st4;
	st4.assign("hello,C++");
	cout << st4 << endl;
	//4.透過assign,把前n個字元賦值
	string st5;
	st5.assign("hello C++", 6);
	cout << st5 << endl;
	//5.透過assign把字串物件給
	string st6;
	st6 = st5;
	cout << st6 << endl;
	//6.透過assign把n個相同字元賦個string
	string st7;
	st7.assign(10, 'a');
	cout << st7 << endl;
}

string的拼接操作

image

void test01()
{
	const char* ch = "hello world,";
	string st;
	//1.過載+=符號,後面可以跟常量字串/字元陣列,字元,以及字串
	st += ch;
	st += " I am ";
	st += 'a'; st += ' ';
	string st2 = "Chinese";
	st += st2;
	cout << st << endl;
	//2.採用append函式,可以跟常量字串/字元陣列,陣列的前n個字元,字串以及從特定位置的n個字元開始拼接
	string s;
	s.append(ch);
	s.append(" I am ");
	s.append("abcde", 1);
	string s2 = "I am a Chinese";
	s.append(s2,6,8);
	cout << s << endl;

}

相關文章