好的,以下是C++标准库学习笔记的markdown格式文档。希望能够帮助您加深对C++标准库的理解。

C++ 标准库学习笔记

容器

vector

vector是一个动态数组容器,支持在末尾添加和删除元素,并且能够通过下标访问和修改元素。使用vector需要包含头文件<vector>。以下是一些使用vector的例子:

c++Copy Code
#include <iostream> #include <vector> using namespace std; int main() { // 创建一个空的vector vector<int> v1; // 在末尾添加元素 v1.push_back(1); v1.push_back(2); v1.push_back(3); // 通过下标访问和修改元素 cout << "v1[0] = " << v1[0] << endl; v1[0] = 4; cout << "v1[0] = " << v1[0] << endl; // 删除末尾元素 v1.pop_back(); // 遍历vector中的元素 for (auto i : v1) { cout << i << " "; } cout << endl; return 0; }

list

list是一个双向链表容器,支持在任意位置添加和删除元素,并且能够进行快速的插入和删除操作。使用list需要包含头文件<list>。以下是一些使用list的例子:

c++Copy Code
#include <iostream> #include <list> using namespace std; int main() { // 创建一个空的list list<int> l1; // 在末尾添加元素 l1.push_back(1); l1.push_back(2); l1.push_back(3); // 在任意位置添加元素 auto it = l1.begin(); ++it; l1.insert(it, 4); // 删除任意位置的元素 it = l1.begin(); ++it; l1.erase(it); // 遍历list中的元素 for (auto i : l1) { cout << i << " "; } cout << endl; return 0; }

map

map是一个关联容器,支持快速查找和插入键值对,并且能够根据键排序。使用map需要包含头文件<map>。以下是一些使用map的例子:

c++Copy Code
#include <iostream> #include <map> using namespace std; int main() { // 创建一个空的map map<string, int> m1; // 插入键值对 m1.insert(make_pair("apple", 1)); m1.insert(make_pair("banana", 2)); m1.insert(make_pair("cherry", 3)); // 查找键对应的值 cout << "m1[\"banana\"] = " << m1["banana"] << endl; // 遍历map中的键值对 for (auto i : m1) { cout << i.first << " -> " << i.second << endl; } return 0; }

算法

sort

sort是一个常用的排序算法,支持对数组、vector等容器进行排序。使用sort需要包含头文件<algorithm>。以下是一个使用sort对vector进行排序的例子:

c++Copy Code
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { // 创建一个vector vector<int> v1 = {3, 2, 1}; // 对vector进行排序 sort(v1.begin(), v1.end()); // 输出排序后的vector for (auto i : v1) { cout << i << " "; } cout << endl; return 0; }

find

find是一个常用的查找算法,支持在数组、vector等容器中查找元素。使用find需要包含头文件<algorithm>。以下是一个使用find在vector中查找元素的例子:

c++Copy Code
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { // 创建一个vector vector<int> v1 = {1, 2, 3}; // 查找元素 auto it = find(v1.begin(), v1.end(), 2); if (it != v1.end()) { cout << "Found " << *it << endl; } else { cout << "Not found" << endl; } return 0; }

其他

字符串

string是一个字符串容器,支持字符串的拼接、查找、替换等操作。使用string需要包含头文件<string>。以下是一些使用string的例子:

c++Copy Code
#include <iostream> #include <string> using namespace std; int main() { // 创建一个空的string string s1; // 在末尾添加字符 s1.push_back('a'); s1.push_back('b'); s1.push_back('c'); // 字符串的拼接 string s2 = "def"; s1 += s2; // 查找子串 auto pos = s1.find("bc"); if (pos != string::npos) { cout << "Found at position " << pos << endl; } else { cout << "Not found" << endl; } // 替换子串 s1.replace(pos, 2, "xy"); // 输出字符串 cout << s1 << endl; return 0; }

以上是C++标准库学习笔记的部分内容,希望能够对您有所帮助。