STL(標準模板庫)是C++標準庫的重要組成部分,包含容器、迭代器和算法三大核心組件。1. 容器如vector、map、set用于存儲數(shù)據(jù);2. 迭代器用于訪問容器元素;3. 算法如sort、find用于操作數(shù)據(jù)。選擇容器時,vector適合動態(tài)數(shù)組,list適合頻繁插入刪除,deque支持雙端快速操作,map/unordered_map用于鍵值對查找,set/unordered_set用于去重。使用算法時應(yīng)包含<algorithm>頭文件,并配合迭代器和lambda表達式。注意避免失效迭代器、刪除時更新迭代器、不可修改map/set的key值,或使用范圍for循環(huán)提高安全性。掌握STL能顯著提升代碼效率與可讀性。
如果你剛開始學 C++,可能已經(jīng)聽說過 STL 這個詞。它全稱是 Standard Template Library(標準模板庫),是 C++ 中非常強大的一部分,提供了一系列通用的數(shù)據(jù)結(jié)構(gòu)和算法。這篇文章不會從頭講語法,而是直接帶你了解 STL 的核心組成、如何使用常見容器和算法,并給出一些實用建議。

什么是 STL,為什么重要?
STL 是 C++ 標準庫的一部分,主要包含三個核心組件:容器(Containers)、迭代器(Iterators) 和 算法(Algorithms)。它們共同作用,讓你可以高效地處理數(shù)據(jù)。

- 容器用來存儲數(shù)據(jù),比如
vector
、map
、set
。 - 迭代器像指針一樣用來訪問容器中的元素。
- 算法則是對這些數(shù)據(jù)進行操作的函數(shù),例如排序、查找等。
用 STL 的好處在于你不用自己實現(xiàn)鏈表、動態(tài)數(shù)組這些基礎(chǔ)結(jié)構(gòu),而且代碼會更簡潔、可讀性更高。
常見容器怎么選?看需求
C++ 提供了多種容器類型,每種適用于不同場景。以下是最常用的幾個:

-
vector
:動態(tài)數(shù)組,適合順序訪問,尾部插入/刪除快。 -
list
:雙向鏈表,適合頻繁在中間插入或刪除元素。 -
deque
:雙端隊列,支持兩端快速插入。 -
map
/unordered_map
:鍵值對集合,前者基于紅黑樹有序,后者基于哈希無序但更快。 -
set
/unordered_set
:集合類型,用于去重,同理有有序和無序之分。
舉個例子,如果你需要一個列表,隨時添加元素又不確定大小,首選 vector
;如果要根據(jù)關(guān)鍵字快速查找,就用 map
或 unordered_map
。
小提示:盡量避免用
vector<bool>
,這個特化版本行為跟普通 vector 不太一樣,容易踩坑。
算法怎么用?別自己造輪子
STL 提供了大量的算法函數(shù),都在 <algorithm>
頭文件里。常見的如:
-
sort()
:排序 -
find()
:查找元素 -
copy()
:復(fù)制數(shù)據(jù) -
transform()
:轉(zhuǎn)換數(shù)據(jù)
這些函數(shù)通常接受兩個迭代器作為參數(shù),表示操作范圍。例如:
#include <algorithm> #include <vector> std::vector<int> v = {5, 2, 8, 1}; std::sort(v.begin(), v.end()); // 排序后變成 {1, 2, 5, 8}
你可以配合 lambda 表達式來自定義排序規(guī)則或者判斷條件,這樣寫出來的代碼既簡潔又靈活。
注意:有些算法返回的是迭代器而不是索引,使用前記得檢查是否合法(比如
find()
找不到時返回end()
)。
使用迭代器時要注意什么?
迭代器是連接容器和算法的橋梁,但在使用過程中有幾個地方容易出錯:
- 避免使用已經(jīng)失效的迭代器。例如你在遍歷
vector
時進行了擴容操作(比如push_back
),可能會導(dǎo)致迭代器失效。 - 刪除元素時注意更新迭代器。例如使用
list.erase(it++)
是一種常見做法。 - 在使用
map
或set
時,不要嘗試修改 key 的值,因為這會影響內(nèi)部結(jié)構(gòu)。
如果你不太確定迭代器的行為,可以用范圍 for 循環(huán)來簡化操作,比如:
for (const auto& item : my_vector) { std::cout << item << std::endl; }
這種方式更直觀,也更安全。
基本上就這些。STL 是 C++ 編程中不可或缺的一部分,掌握好常用容器和算法,能讓你寫出更清晰、高效的代碼。雖然一開始可能會覺得有點抽象,但多用幾次就能上手了。
The above is the detailed content of C tutorial on the Standard Template Library (STL). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

There are mainly the following methods to obtain stack traces in C: 1. Use backtrace and backtrace_symbols functions on Linux platform. By including obtaining the call stack and printing symbol information, the -rdynamic parameter needs to be added when compiling; 2. Use CaptureStackBackTrace function on Windows platform, and you need to link DbgHelp.lib and rely on PDB file to parse the function name; 3. Use third-party libraries such as GoogleBreakpad or Boost.Stacktrace to cross-platform and simplify stack capture operations; 4. In exception handling, combine the above methods to automatically output stack information in catch blocks

In C, the POD (PlainOldData) type refers to a type with a simple structure and compatible with C language data processing. It needs to meet two conditions: it has ordinary copy semantics, which can be copied by memcpy; it has a standard layout and the memory structure is predictable. Specific requirements include: all non-static members are public, no user-defined constructors or destructors, no virtual functions or base classes, and all non-static members themselves are PODs. For example structPoint{intx;inty;} is POD. Its uses include binary I/O, C interoperability, performance optimization, etc. You can check whether the type is POD through std::is_pod, but it is recommended to use std::is_trivia after C 11.

To call Python code in C, you must first initialize the interpreter, and then you can achieve interaction by executing strings, files, or calling specific functions. 1. Initialize the interpreter with Py_Initialize() and close it with Py_Finalize(); 2. Execute string code or PyRun_SimpleFile with PyRun_SimpleFile; 3. Import modules through PyImport_ImportModule, get the function through PyObject_GetAttrString, construct parameters of Py_BuildValue, call the function and process return

In C, there are three main ways to pass functions as parameters: using function pointers, std::function and Lambda expressions, and template generics. 1. Function pointers are the most basic method, suitable for simple scenarios or C interface compatible, but poor readability; 2. Std::function combined with Lambda expressions is a recommended method in modern C, supporting a variety of callable objects and being type-safe; 3. Template generic methods are the most flexible, suitable for library code or general logic, but may increase the compilation time and code volume. Lambdas that capture the context must be passed through std::function or template and cannot be converted directly into function pointers.

AnullpointerinC isaspecialvalueindicatingthatapointerdoesnotpointtoanyvalidmemorylocation,anditisusedtosafelymanageandcheckpointersbeforedereferencing.1.BeforeC 11,0orNULLwasused,butnownullptrispreferredforclarityandtypesafety.2.Usingnullpointershe

std::move does not actually move anything, it just converts the object to an rvalue reference, telling the compiler that the object can be used for a move operation. For example, when string assignment, if the class supports moving semantics, the target object can take over the source object resource without copying. Should be used in scenarios where resources need to be transferred and performance-sensitive, such as returning local objects, inserting containers, or exchanging ownership. However, it should not be abused, because it will degenerate into a copy without a moving structure, and the original object status is not specified after the movement. Appropriate use when passing or returning an object can avoid unnecessary copies, but if the function returns a local variable, RVO optimization may already occur, adding std::move may affect the optimization. Prone to errors include misuse on objects that still need to be used, unnecessary movements, and non-movable types

The key to an abstract class is that it contains at least one pure virtual function. When a pure virtual function is declared in the class (such as virtualvoiddoSomething()=0;), the class becomes an abstract class and cannot directly instantiate the object, but polymorphism can be realized through pointers or references; if the derived class does not implement all pure virtual functions, it will also remain an abstract class. Abstract classes are often used to define interfaces or shared behaviors, such as designing Shape classes in drawing applications and implementing the draw() method by derived classes such as Circle and Rectangle. Scenarios using abstract classes include: designing base classes that should not be instantiated directly, forcing multiple related classes to follow a unified interface, providing default behavior, and requiring subclasses to supplement details. In addition, C
