Timeline
Timeline
2025-10-03
init
2025-10-12
add next_permutation to generate all permutations of a sequence
2025-10-19
add string
This article introduces the basic syntax of the C++ programming language and the core components of the Standard Template Library (STL). It discusses in detail the concepts of lvalues, rvalues, and reference types, the operation methods of standard input/output streams and sstream string streams, and summarizes the usage and time complexity of common containers such as vector, queue, and priority_queue.
Syntax
& and &&, lvalues and rvalues
Lvalue
Has a name and can have its address taken.
Can appear on the left side of an assignment operator.
Example:
1
2
3int x = 5; // x is an lvalue
x = 10; // Can be assigned
int* p = &x; // Can have its address taken
Rvalue
Temporary objects or literals, without a name, cannot have their address taken.
Usually appears on the right side of the assignment operator.
Example:
1
2int y = x + 2; // x+2 is an rvalue
int z = 42; // 42 is an rvalue
Note: Rvalues can bind to rvalue references (
&&)。Reference types
| Reference | Meaning |
|---|---|
T& | Lvalue reference (can only bind to lvalues) |
T&& | Rvalue reference (can only bind to rvalues) |
Example:
1 | int a = 5; |
- Lvalue references can modify lvalues:
1 | lref = 10; // a = 10 |
- Rvalue references are commonly used for move semantics:
1 | vector<int> v1 = {1,2,3}; |
Input and Output
Input
First, in C++, to use standard input, you need to include the header file
cin
cin is the standard input stream object in C++. Below are two uses of cin: single read and batch read. The principle of cin is, simply put, that there is a buffer. Data entered from the keyboard is first stored in the buffer, and cin can read data from the buffer.
Note 1: cin can continuously read data from the keyboard
Note 2: cin uses spaces, tabs, and newline characters as delimiters
Note 3: cin starts reading from the first non-space character and stops reading when it encounters a delimiter
getline()
1 | istream& getline (char* s, streamsize n ); |
From the notes on cin, it can also be seen that when the string we want to read contains spaces, cin will not read the entire string. In this case, the getline() function can be used to solve the problem.
Note 1: When using the getline() function, you need to include the header file<string>
Note 2: The getline() function reads a line, and the read string includes spaces, ending when a newline character is encountered
getchar()
This function reads a character from the buffer and is often used to determine whether a newline occurs
Output
Similarly, in C++, to use standard output, you also need to include the header file<iostream>
On the output side, we mainly introduce one function, which is the most commonly used.coutIt should be noted that if outputtingendlan object, a newline character will be output, similar to\n。
sstream
Include header file
1 |
|
Three classes
| Class Name | Function | Scenario |
|---|---|---|
stringstream | Supports both reading and writing | General purpose |
istringstream | Read-only input stream | Parse string |
ostringstream | Write-only output stream | Construct string |
Common operations:
| Function | Purpose | Example |
|---|---|---|
str() | Get/Set Internal String | ss.str("123 456") |
clear() | Clear Stream State | Must be called when reusing |
operator>> | Extract Data (Split by Whitespace) | ss >> x; |
operator<< | Insert Data | ss << 42; |
getline() | Read by Line | getline(ss, s) |
good()fail() | Check Stream State | Determine if Parsing Succeeded |
Note: Must call clear when reusing
Example:
Split String
1 |
|
| Usage | Method | Example | Description | Common Pitfall |
|---|---|---|---|---|
| Whitespace Tokenization | ss >> word | ss >> w1 >> w2 | Split by spaces, newlines, and tabs | Does not split on non-whitespace like commas |
| Custom Delimiter | getline(ss, word, ',') | getline(ss, word, ','); | Split by,splitting | Must usegetline,>>Cannot customize delimiter |
| Parsing Numbers | ss >> num | int x; ss >> x; | String numbers to int/double | Non-numeric values cause stream failure, must checkss.fail() |
| Concatenate strings | oss << val | oss << "ID=" << 5; | Efficiently construct dynamic strings | After output endsoss.str()Can only get the complete content |
STL
vector
Include header file
1 |
|
Construction
1 | // Empty vector |
Access elements
Returns a reference to the element
Access with bounds checking throws if out of boundsstd::out_of_rangeexception
1 | // Access by index (without bounds checking) |
Modify elements
1 | v[2] = 10; // Modify the value at index 2 |
Iterate over elements
1 | // Index-based iteration |
Time complexity
| Operation | Time complexity | Description |
|---|---|---|
v[i] | O(1) | Random access |
v.at(i) | O(1) | Random access with bounds checking |
push_back(x) | O(1) amortized | Average constant time, occasional O(n) reallocation |
pop_back() | O(1) | Remove last element |
insert(v.begin() + i, x) | O(n) | Insert in middle, average move n/2 elements |
erase(v.begin() + i) | O(n) | Remove middle element, average move n/2 elements |
front()/back() | O(1) | Access first/last element |
size()/empty() | O(1) | Get size / check if empty |
clear() | O(n) | Clear elements (destructor call) |
sort(v.begin(), v.end()) | O(n log n) | Sort using STL algorithms |
queue
Include header file
1 |
|
Construction
1 | // Empty queue |
Access front and back of queue
1 | // View front/back element |
Enqueue and dequeue
1 | // Enqueue (insert at back) |
Time complexity
| Operation | Time complexity |
|---|---|
push() | O(1) |
pop() | O(1) |
front() | O(1) |
back() | O(1) |
empty() | O(1) |
size() | O(1) |
priority_queue
Priority queue, internally uses max-heap by default
When dequeuing, always pop thelargest element(default max-heap).
A custom comparator can be used to implementa min-heap。
priority_queue has no iterators; traversal can only be done using pop() and top()
Include header file
1 |
|
Construction
The template parameters of priority_queue: the first is the element type, the second is the underlying container (default vector), and the third is the comparator
Note that priority_queue only supports popping the top; it does not support directly modifying or deleting a specific element in the heap
- If you want to delete a specific element from priority_queue, consider whether you can use unordered_map to implementlazy deletion(only delete when the invalid element reaches the top, otherwise just mark it)
1 | // Default constructor |
Access top of heap
1 | priority_queue<int> pq; |
Pop top element of heap
1 | pq.pop(); |
Custom comparator
Method 1: Use std::greater
1 | priority_queue<int, vector<int>, std::greater<int>> min_pq; |
Method 2: Custom struct/lambda
1 | struct cmp { |
Method 3: If it’s a struct, directly overload < operator
1 | struct Person { |
Time Complexity
| Operation | Average Complexity |
|---|---|
push | O(log n) |
pop | O(log n) |
top | O(1) |
size | O(1) |
empty | O(1) |
stack
Stack, Last In First Out
stackNo iterator, cannot usefordirect loop traversal. Traversal can only be done viatop()+pop()。
Include Header File
1 |
|
Construction
1 | stack<int> s1; // Empty Stack |
Push/Pop
1 | stack<int> s; |
Access Top Element
1 | // View Top Element |
time complexity
| operation | average complexity |
|---|---|
push | O(1) |
pop | O(1) |
top | O(1) |
size | O(1) |
empty | O(1) |
map, unordered_map
map
mapisordered associative container, typically implemented usingred-black tree.Each element is akey-valuepair, with unique keys, automatically sorted by key.
Suitable for scenarios requiringaccess in key order.
unordered_map
unordered_mapisHash table, stores key-value pairs in no particular order.- Average time complexity for search, insertion, and deletion is O(1).
- Suitable for fast lookups,order is not important。
GCC’s
unordered_maphas had an optimization since C++11:
- When the linked list in a bucket exceeds a certain threshold (usually 8), the list is converted to a red-black tree。
- This preventsthe O(n) complexity caused by worst-case hash collisions, reducing lookup complexity from O(n) to O(log n).
- That is:linked list → red-black tree, rather than the entire hash table degenerating into a red-black tree.
Include header file
map
1 | // map |
unordered_map
1 | // unordered_map |
Construction
map
1 | // Empty map |
unordered_map
1 | // Empty table |
Access element
map
1 | map<int, string> m; |
unordered_map
1 | unordered_map<int, string> um; |
Insert, modify, and element
map
1 | map<int, string> m; |
unordered_map
1 | unordered_map<int, string> um; |
Find element
map
1 | map<int, string> m; |
unordered_map
1 | unordered_map<int, string> um; |
Delete element
map
1 | map<int, string> m; |
unordered_map
1 | unordered_map<int, string> um; |
Traverse
map
Map is traversed in order by key
1 | map<int, string> m; |
unordered_map
Note:
unordered_mapis unordered, and the traversal order is not fixed.
1 | for (auto &[key, value] : um) { |
Custom comparator (map only)
1 | map<int, string, std::greater<int>> m; // Sort by key in descending order |
Time complexity
map
| Operation | Average complexity |
|---|---|
| Insert/Delete | O(log n) |
| Search | O(log n) |
| Traversal | O(n) |
| Access element | O(log n) |
unordered_map
| Operation | Average complexity | Worst-case complexity |
|---|---|---|
| Insert | O(1) | O(n) |
| find | O(1) | O(n) |
| delete | O(1) | O(n) |
| traverse | O(n) | O(n) |
set, unordered_set
- set
setisordered set, usually implemented withred-black tree.- Storesunique elements, automatically sorted by element size.
- Suitable for scenarios requiringordered access and fast lookup of unique elements.
- unordered_set
unordered_setisHash table set, stores unique elements in no particular order.- Average search, insertion, and deletion complexity is O(1).
- Suitable for fast lookups when order is not important.
GCC’s
unordered_setalso supportstreeification within buckets when the linked list length exceeds a threshold, avoiding the worst-case O(n).
Include header file
set
1 |
|
unordered_set
1 |
|
Construction
set
1 | set<int> s1; // Empty set |
unordered_set
1 | unordered_set<int> us1; // Empty set |
Insertion and modification
set
1 | set<int> s; |
unordered_set
1 | unordered_set<int> us; |
Find element
set
1 | set<int> s = {1,2,3}; |
unordered_set
1 | unordered_set<int> us = {1,2,3}; |
Delete element
set
1 | s.erase(2); // Delete by element value |
unordered_set
1 | us.erase(2); |
Traversal
set
Traverse in ascending order of elements
1 | for (auto &val : s) { |
unordered_set
Traversal order is not fixed
1 | for (auto &val : us) { |
Custom comparator (only supported by set)
1 | set<int, std::greater<int>> s; // Sorted in descending order |
Time complexity
set
| Operation | Average complexity |
|---|---|
| Insert/Delete | O(log n) |
| Search | O(log n) |
| Traversal | O(n) |
unordered_set
| Operation | Average complexity | Worst-case complexity |
|---|---|---|
| Insert | O(1) | O(n) |
| Search | O(1) | O(n) |
| Delete | O(1) | O(n) |
| traverse | O(n) | O(n) |
string
In most modern C++ compilers (such as GCC/Clang/MSVC),std::stringthe implementation is similar to:
- Internally usesa dynamic arrayto store characters
- automatically maintains a trailing
'\0'(compatible with C-string) - Each
stringalso maintainssizeandcapacity
String expansion usually follows**exponential growth (e.g., doubling)**to reduce repeated memory allocations.
Small String Optimization (SSO)
SSO isstd::stringa core performance optimization technique.
Purpose: Reduce heap memory allocation and speed up small string operations.
When the string length is short (typically ≤ 15 characters), many implementations willstore it directly in a small buffer inside the object, without allocating heap memory.
1 | string s = "hello"; // Likely no heap memory allocation (SSO) |
Advantages:
- Avoid frequent
new/delete - Improve performance
- Reduce memory fragmentation
Include header file
1 |
|
Construction
| Construction method | Prototype | Description | Example |
|---|---|---|---|
| Default constructor | string() | Create empty string | string s1; // "" |
| Copy constructor | string(const string& str) | Copy existing string | string s2(s1); |
| Move constructor | string(string&& str) | Move existing string (since C++11) | string s3(std::move(s1)); |
| C string | string(const char* s) | From a C string ending with\0null-terminated C string | string s4("hello"); |
| C string + length | string(const char* s, size_t n) | Take only first n characters | string s5("hello world", 5); // "hello" |
| Repeated character | string(size_t n, char c) | Create string of n identical characters | string s6(4, 'a'); // "aaaa" |
| Range construction | template<class InputIt> string(InputIt first, InputIt last) | Initialize with iterator range | vector<char> v{'x','y','z'}; string s7(v.begin(), v.end()); |
| initializer_list | string(std::initializer_list<char> ilist) | Initialize with list of characters (C++11) | string s8({'a','b','c'}); // "abc" |
Default construction
1 | string s1; |
- Common pitfalls: Empty string’s
c_str()is still valid, returns""。
Copy construction
1 | string s2("hello"); |
- Performance advice: For large strings, prefer using
const string&pass by reference to avoid copying
Move construction (C++11+)
1 | string s4(std::move(s2)); |
- Characteristics:
s2The content is moved, the original object becomes empty - Advantages: Avoid copying memory to improve performance
C string construction
1 | string s5("hello"); |
- Use cases: Initialize from literals or C-style arrays
- Performance tips: If the length is known, use the second parameter to avoid redundant scanning
- Common pitfalls: Passing a non-
\0null-terminated string requires specifying the length
Repeated character construction
1 | string s7(5, 'x'); // "xxxxx" |
Range construction (iterators)
1 | vector<char> v{'a','b','c'}; |
Initializer_list construction (C++11+)
1 | string s9({'x','y','z'}); // "xyz" |
Access and assignment operations
Subscript accessoperator[]
1 | string s = "hello"; |
Description:
No bounds checking is performed; accessing out-of-bounds leads to undefined behavior.
After move construction or reallocation, pointers or references to the original characters may become invalid.
Safe Accessat()
1 | char c = s.at(1); // 'e' |
- Description:
- Performs range checking and throws
std::out_of_rangeexception on out-of-bounds access.
- Performs range checking and throws
Accessing First and Last Characters
1 | char f = s.front(); // 'H' |
- Description:
- Calling
front()orback()on an empty string is undefined behavior.
- Calling
- Common Pitfall:
- Accessing an empty string triggers UB (undefined behavior).
String Assignment assign()
assign()isstd::stringVersatile assignment functions with rich overloading:
| Prototype | Description | Example |
|---|---|---|
string& assign(const string& str) | Copy another string | s.assign(s2); |
string& assign(string&& str) | Move another string | s.assign(std::move(s2)); |
string& assign(const string& str, size_t pos, size_t count) | Assign from a substring of str | s.assign(s2, 1, 3); // 取 s2[1..3] |
string& assign(const char* s) | C-string assignment | s.assign("world"); |
string& assign(const char* s, size_t n) | Assign first n characters | s.assign("hello world", 5); // "hello" |
string& assign(size_t n, char c) | Assign repeated characters | s.assign(4, 'x'); // "xxxx" |
template<class InputIt> string& assign(InputIt first, InputIt last) | Range assignment | vector<char> v{'a','b'}; s.assign(v.begin(), v.end()); |
string& assign(initializer_list<char> il) | Initializer list assignment (C++11+) | s.assign({'x','y','z'}); // "xyz" |
Modifying operations
Append
| Prototype | Description | Example |
|---|---|---|
string& append(const string& str) | Append entire string | s.append(s2); |
string& append(const string& str, size_t pos, size_t count) | Append substring of str | s.append(s2, 1, 3); |
string& append(const char* s) | Append C string | s.append("world"); |
string& append(const char* s, size_t n) | Append first n characters of C string | s.append("hello world", 5); // "hello" |
string& append(size_t n, char c) | Append n identical characters | s.append(3, '!'); // "!!!" |
template<class InputIt> string& append(InputIt first, InputIt last) | Append range | vector<char> v{'a','b'}; s.append(v.begin(), v.end()); |
string& push_back(char c) | Append single character | s.push_back('x'); |
Performance advice
Optimize concatenation — default concatenation is inefficient
1 | string s; |
- For frequent modifications, use
std::ostringstreamorstd::string_view
Insert
| Prototype | Description | Example |
|---|---|---|
string& insert(size_t pos, const string& str) | Insert entire string at pos | s.insert(2, s2); |
string& insert(size_t pos, const string& str, size_t subpos, size_t count) | Insert substring of str | s.insert(1, s2, 0, 2); |
string& insert(size_t pos, const char* s) | Insert C string | s.insert(0, "Hi"); |
string& insert(size_t pos, const char* s, size_t n) | Insert first n characters of C string | s.insert(0, "Hello World", 5); |
string& insert(size_t pos, size_t n, char c) | Insert n identical characters | s.insert(3, 4, '*'); |
iterator insert(const_iterator p, char c) | Insert single character | s.insert(s.begin()+1, 'x'); |
template<class InputIt> void insert(const_iterator p, InputIt first, InputIt last) | Insert range | s.insert(s.begin(), v.begin(), v.end()); |
Erase
| Prototype | Description | Example |
|---|---|---|
string& erase(size_t pos = 0, size_t count = npos) | Erase count characters starting from pos | s.erase(2,3); |
iterator erase(const_iterator p) | Delete character pointed by iterator | s.erase(s.begin()+1); |
iterator erase(const_iterator first, const_iterator last) | Delete range | s.erase(s.begin(), s.begin()+3); |
Replace
| Prototype | Description | Example |
|---|---|---|
string& replace(size_t pos, size_t count, const string& str) | Replace count characters starting from pos with str | s.replace(0,2,"Hi"); |
string& replace(size_t pos, size_t count, const string& str, size_t subpos, size_t subcount) | Replace with substring of str | s.replace(0,2,s2,1,2); |
string& replace(size_t pos, size_t count, const char* s) | Replace with C string | s.replace(0,2,"OK"); |
string& replace(size_t pos, size_t count, const char* s, size_t n) | Replace with first n characters of C string | s.replace(0,2,"Hello World",5); |
string& replace(size_t pos, size_t count, size_t n, char c) | Replace with n identical characters | s.replace(0,2,3,'*'); |
iterator replace(const_iterator first, const_iterator last, InputIt first2, InputIt last2) | Replace iterator range | s.replace(s.begin(), s.begin()+2,v.begin(),v.end()); |
Find operation
| Function prototype | Description | Example |
|---|---|---|
size_t find(const string& str, size_t pos=0) const | Find first occurrence of substring starting from pos | s.find("world"); // 6 |
size_t find(const char* s, size_t pos=0) const | Find C string starting from pos | s.find("lo"); // 3 |
size_t find(const char* s, size_t pos, size_t n) const | Find first n characters of C string | s.find("hello world", 0, 5); // 查找 "hello" |
size_t find(char c, size_t pos=0) const | Find first occurrence of character | s.find('o'); // 4 |
size_t rfind(const string& str, size_t pos=npos) const | Find substring from right to left | s.rfind("lo"); |
size_t rfind(char c, size_t pos=npos) const | Find character from right to left | s.rfind('o'); |
size_t find_first_of(const string& chars, size_t pos=0) const | Find first occurrence of any character from specified set | s.find_first_of("aeiou"); |
size_t find_last_of(const string& chars, size_t pos=npos) const | Find last occurrence of any character from set | s.find_last_of("aeiou"); |
size_t find_first_not_of(const string& chars, size_t pos=0) const | Find first position not in character set | s.find_first_not_of("aeiou"); |
size_t find_last_not_of(const string& chars, size_t pos=npos) const | Find last position not in character set | s.find_last_not_of("aeiou"); |
String comparison
| Function prototype | Description | Example | Performance |
|---|---|---|---|
int compare(const string& str) const | Compare entire string with str | s.compare("hello"); | O(min(n, m)) |
int compare(size_t pos, size_t count, const string& str) const | Compare substring[pos, pos+count)with str | s.compare(0,2,"he"); | O(count) |
int compare(size_t pos, size_t count, const string& str, size_t subpos, size_t subcount) const | Compare s substring with str substring | s.compare(0,2,s2,1,2); | O(subcount) |
int compare(const char* s) const | Compare with C string | s.compare("hello"); | O(n) |
int compare(size_t pos, size_t count, const char* s) const | Compare substring with C string | s.compare(0,2,"he"); | O(count) |
int compare(size_t pos, size_t count, const char* s, size_t n) const | Compare substring with first n characters of C string | s.compare(0,2,"hello",2); // "he" | O(n) |
Return value:
Return value less than 0: s < str,
Return value equal to 0: s == str,
Return value greater than 0: s > str
Can also compare using operators
| Operators | Function | Example | Return Type | Comparison Method |
|---|---|---|---|---|
== | Check Equality | s == "hello" | bool | Case-Sensitive & Character-by-Character Comparison |
!= | Check Inequality | s != t | bool | Same as Above |
< | Lexicographically Less Than | "abc" < "abd" | bool | Compare by ASCII/Unicode |
<= | Less Than or Equal | "abc" <= "abc" | bool | Same as Above |
> | Lexicographically Greater Than | "dog" > "cat" | bool | Same as Above |
>= | Greater Than or Equal | "hi" >= "ha" | bool | Same as Above |
substring
| Function Prototype | Description | Example | Return Value | Note | Performance |
|---|---|---|---|---|---|
string substr(size_t pos = 0, size_t count = npos) const | From positionposstart, extract length ofcountsubstring | s.substr(2, 4) | Returns a new string | pos > size()Throws exception | Creates a new string copy, be mindful of performance |
Character checking and case conversion
Need to include C standard library
1 |
Common character judgment functions
| Function | Purpose | Example |
|---|---|---|
isalnum(c) | Is it alphanumeric | 'A','z','3' |
isalpha(c) | Is it a letter | 'A','b' |
isdigit(c) | Is it a digit | '0'~'9' |
islower(c) | Is it a lowercase letter | 'a' |
isupper(c) | Is it an uppercase letter | 'Z' |
isspace(c) | Is it a whitespace character (space/newline/tab) | ' ','\n','\t' |
ispunct(c) | Is it a punctuation mark | ',' '.' '!' |
isxdigit(c) | Is it a hexadecimal digit | '0'~'9','a'~'f' |
isprint(c) | Is it a printable character | Normal character |
iscntrl(c) | Is it a control character | '\n' '\r' |
Case conversion functions
| Function | Description | Example |
|---|---|---|
tolower(c) | Convert character to lowercase | tolower('A') → 'a' |
toupper(c) | Convert character to uppercase | toupper('b') → 'B' |
These two functionsonly operate on a single character, to process strings, they need to be used withtransform():
1 |
|
::tolowerin::refers tothe global scope operator, indicating the use ofthe global tolower functionto avoid ambiguity caused by having the same name as certain class members.
Conversion between strings and numbers
String to integer conversion function table
| Function | Function prototype | Parameter description | Return value description | Example |
|---|---|---|---|---|
stoi | int stoi(const string& str, size_t* pos = 0, int base = 10); | str: Input stringpos: Returns the number of successfully converted charactersbase: Base (2-36) | Convertedint | stoi("123") → 123stoi("1A", nullptr, 16) → 26 |
stol | long stol(const string& str, size_t* pos = 0, int base = 10); | Same as above | Convert tolong | stol("99999") → 99999L |
stoll | long long stoll(const string& str, size_t* pos = 0, int base = 10); | Same as above | Convert tolong long | stoll("1234567890123") |
stoi(C string) | int stoi(const char* str, size_t* pos = 0, int base = 10); | str: C-style string | convert toint | stoi("42") → 42 |
String to Floating-Point Conversion Function Table
| Function | Function Prototype | Parameter Description | Return Value Description | Example |
|---|---|---|---|---|
stof | float stof(const string& str, size_t* pos = 0); | str: stringpos: returns parsed character length | convert tofloat | stof("3.14") → 3.14f |
stod | double stod(const string& str, size_t* pos = 0); | Same as above | convert todouble | stod("2.71828") |
stold | long double stold(const string& str, size_t* pos = 0); | Same as above | convert tolong double | stold("1.6180339887") |
Number → String Conversion (to_string)
| Function | Function Prototype | Parameter Description | Return Value Description | Example |
|---|---|---|---|---|
to_string | string to_string(int value); | value: Number | Returns the converted string | to_string(42) → "42" |
to_string | string to_string(double value); | Same as above | Float to String | to_string(3.14) → "3.140000" |
to_string | string to_string(long long value); | Same as above | Supports long integer | to_string(1234567890123) |
Return Value and Exception Summary
| Condition | Behavior |
|---|---|
| Input is not a number | Throwstd::invalid_argument |
| Number out of range | Throwstd::out_of_range |
| Automatically trim leading spaces | ✅ Supported" 123" |
| Supports symbols | ✅"-42"" +88" |
| Supports partial parsing | ✅"123abc"→ 123 |
Strings and Streams
Include header file
1 |
|
Three classes
| Class name | Purpose | Scenario |
|---|---|---|
stringstream | Supports both reading and writing | General |
istringstream | Read-only input stream | Parse string |
ostringstream | Write-only output stream | Construct string |
Common operations:
| Function | Purpose | Example |
|---|---|---|
str() | Get/set internal string | ss.str("123 456") |
clear() | Clear stream state | Must be called when reusing |
operator>> | Extract data (split by whitespace) | ss >> x; |
operator<< | Insert data | ss << 42; |
getline() | Read line by line | getline(ss, s) |
good()fail() | Check stream status | Determine if parsing was successful |
Note: must call clear when reusing
Example:
Split string
1 |
|
| Purpose | Method | Example | Description | Common pitfalls |
|---|---|---|---|---|
| Whitespace tokenization | ss >> word | ss >> w1 >> w2 | Split by spaces, newlines, and tabs | Does not split on non-whitespace like commas |
| Custom delimiter | getline(ss, word, ',') | getline(ss, word, ','); | by,split | must usegetline,>>cannot customize delimiter |
| parse numbers | ss >> num | int x; ss >> x; | string numbers → int/double | non-numeric values cause stream failure, need to checkss.fail() |
| concatenate strings | oss << val | oss << "ID=" << 5; | efficiently build dynamic strings | after output endsoss.str()can only get the complete content |
multiset/multimap
multiset
- elementscan be repeated, automatically sorted by key
- underlying usually usesRed-black tree
- Does not support access via subscript; only iterators can be used
- Suitable for scenarios requiringfast lookup and sequential traversal of duplicate elements
multimap<K,V>
- key duplicates allowed, sorted by key
- Underlying implementation typically usesred-black tree
- Can use
equal_rangeto find all elements with a given key
Include header file
1 | // multiset |
Construction
multiset
1 | multiset<int> ms; // Empty multiset |
multimap
1 | multimap<int,string> mm; // empty multimap |
insert element
1 | // multiset |
find element
1 | // multiset |
delete element
1 | // multiset |
traverse
1 | // multiset |
time complexity
| operation | multiset / multimap |
|---|---|
| insert | O(log n) |
| search | O(log n) |
| delete | O(log n) |
| traverse | O(n) |
tuple
include header file
1 |
|
construct
1 |
|
access element
- cannot access like pair, use std::get<0>(tuple)
note: getrequires index to be a constant known at compile time, so cannot use it to traverse
1 | int a = std::get<0>(tp); |
- since C++17, structured bindings can be used, which is more elegant
1 | auto [a, b, c] = tuple; |
- You can also use std::tie
1 | int a, b, c; |
Modify
1 | std::get<1>(t) = 6; |
Get length
1 | // Tuple length |
Traverse
Not commonly used, use structured binding + fold expression
1 | auto tp = make_tuple(1, 2.5, "hi"); |
algorithm
Include header file
1 |
sort
Basic usage
1 |
|
Custom comparator
1 | struct Person { |
The standard requirement of std::sort is that stability is not guaranteed. If stable sorting is needed, please use std::stable_sort
- Stable sort: If two elements are equal, their relative order before sorting remains unchanged after sorting.
- Unstable sort: The relative order of equal elements may be disrupted after sorting.
min, max
Basic usage
1 | int a = 5, b = 10; |
Custom comparator
1 | struct Person { |
Accepts initializer_list (C++11 and later)
1 | int x = std::min({3, 1, 4, 2}); // x = 1 |
min_element/max_element
min_element and max_Iterator returned by element
1 | vector<int> v= {1,2,4,8}; |
reverse
Reverse ordered container
1 | vector<int> v = {1,2,4,8}; |
find
- Sequentially find the first element equal to a given value in the range, returns an iterator. Returns
end。
1 | vector<int> v = {1, 3, 5, 7}; |
count
- Count occurrences of a value in the range
1 | vector<int> v = {1,2,2,3,2}; |
transform
1 | // Unary Operation |
Example:
1 | std::transform(s.begin(), s.end(), s.begin(), ::tolower); |
Usingunary version(Unary Operation), meaning:
- Input range:
[s.begin(), s.end()) - Output range start:
s.begin()(modify string in place) - Apply operation to each character:
::tolower
::tolowerin::refers toglobal scope operator, meaning usingthe global tolower functionto avoid ambiguity caused by having the same name as certain class members.
You can also not usetolower, pass your own processing logic:
1 | transform(s.begin(), s.end(), s.begin(), [](char c) { |
Two-parameter transformation
Add two array elements
1 |
|
binary_search
- Perform binary search on a sorted sequence, returning
bool, determine if it exists
1 | vector<int> v = {1,3,5,7}; |
lower_bound/upper_bound
- Return iterator,Requires the sequence to be sorted
lower_bound(begin,end,val): returns the first**>= val**positionupper_bound(begin,end,val): returns the first**> val**position
1 | vector<int> v = {1,2,2,3,5}; |
equal_range
- return
[lower_bound, upper_bound)iterator pair, the range contains all elements equal to the given value
1 | auto range = std::equal_range(v.begin(), v.end(), 2); |
next_permutation/prev_permutation
generate the next lexicographical permutation, can be used forgenerate all permutations of a sequence
1 |
|
output:
1 | 1 2 3 |
- also used forgenerate all combinations of length m from an array
1 |
|
output
1 | 1 2 |
can also use prev_permutation
1 |
|
fill
fill(begin,end,val): Fill the entire range with a specified value
1 | vector<int> v(5); |
iota
iota(begin,end,start): Generate a sequence of consecutive integers
1 |
|
copy / swap / replace / remove / remove_if
copy(begin,end,out_it): Copy a range to another container
1 | vector<int> src = {1,2,3}; |
swap(a,b)/iter_swap(it1,it2): Swap elements
1 | std::swap(a,b); |
replace(begin,end,old_val,new_val): Replace elements in a range
1 | std::replace(v.begin(), v.end(), 2, 5); |
remove(begin,end,val)/remove_if(begin,end,pred): Logical removal (needs to be used witherase)
1 | v.erase(std::remove(v.begin(), v.end(), 5), v.end()); |
set operations
- The sequence must besorted
merge(a,b,out): Merge two sorted sequencesset_union(a,b,out): Unionset_intersection(a,b,out): Intersectionset_difference(a,b,out): Differenceunique(begin,end): Remove consecutive duplicates
1 | vector<int> a = {1,2,2,3}; |
Using std::unique requires elements to be already sorted
accumulate / all_of / any_of / none_of / for_each
accumulate(begin,end,init): Range sum (or custom operation)
1 |
|
all_of(begin,end,pred)/any_of/none_of: Check if range elements satisfy condition
1 | bool all_even = std::all_of(v.begin(), v.end(), [](int x){ return x%2==0; }); |
for_each(begin,end,f): Range traversal
1 | std::for_each(v.begin(), v.end(), [](int &x){ x++; }); |
Time Complexity
| Algorithm | Function | Time Complexity | Example Code |
|---|---|---|---|
| sort | Sort (unstable) | O(n log n) | std::sort(v.begin(), v.end()); |
| stable_sort | stable sort | O(n log² n)worst, averageO(n log n) | std::stable_sort(v.begin(), v.end()); |
| min / max | min/max of two numbers | O(1) | std::min(a,b); std::max(a,b); |
| min_element / max_element | iterator to min/max element in range | O(n) | *std::min_element(v.begin(), v.end()); |
| reverse | reverse range | O(n) | std::reverse(v.begin(), v.end()); |
| find | sequential search | O(n) | auto it = std::find(v.begin(),v.end(),5); |
| count | count occurrences | O(n) | std::count(v.begin(),v.end(),2); |
| binary_search | exists (binary, requires sorted) | O(log n) | std::binary_search(v.begin(),v.end(),5); |
| lower_bound | first**>= val**(binary) | O(log n) | auto it=std::lower_bound(v.begin(),v.end(),2); |
| upper_bound | first**> val**(binary) | O(log n) | auto it=std::upper_bound(v.begin(),v.end(),2); |
| equal_range | return range equal to val | O(log n) | auto r=std::equal_range(v.begin(),v.end(),2); |
| fill | range assignment | O(n) | std::fill(v.begin(), v.end(), 7); |
| iota | consecutive assignment (requires<numeric>) | O(n) | std::iota(v.begin(),v.end(),10); |
| copy | Copy range | O(n) | std::copy(src.begin(),src.end(),dst.begin()); |
| swap / iter_swap | Swap elements | O(1) | std::swap(a,b); |
| replace | Replace specified value | O(n) | std::replace(v.begin(),v.end(),2,5); |
| remove / remove_if | Logical deletion (requireserase) | O(n) | v.erase(std::remove(v.begin(),v.end(),5),v.end()); |
| unique | Remove adjacent duplicates (logical deletion) | O(n) | v.erase(std::unique(v.begin(),v.end()),v.end()); |
| set_union | Union (requires sorted order) | O(n+m) | std::set_union(a.begin(),a.end(),b.begin(),b.end(),back_inserter(out)); |
| set_intersection | Intersection (requires sorted order) | O(n+m) | std::set_intersection(...); |
| set_difference | Difference (requires sorted order) | O(n+m) | std::set_difference(...); |
| merge | Merge two sorted sequences | O(n+m) | std::merge(a.begin(),a.end(),b.begin(),b.end(),out.begin()); |
| accumulate | Range accumulation (requires<numeric>) | O(n) | int sum=std::accumulate(v.begin(),v.end(),0); |
| all_of / any_of / none_of | Range condition check | O(n) | std::all_of(v.begin(),v.end(),[](int x){return x%2==0;}); |
| for_each | Traverse and execute function | O(n) | std::for_each(v.begin(),v.end(),[](int &x){x++;}); |
utility
Include header file
1 |
pair
Include header file
1 |
|
Construction
1 | pair<int,int> p = {1,2}; |
Accessing elements
1 | int a = p.first; |
std::move
std::move actually converts the parameter t to an rvalue reference type, without copying memory, releasing resources, or calling constructors and destructors
1 | template <typename T> |
Take std::vector
1 | std::vector<int> a = {1, 2, 3}; |
Here: std::move(a) turns a into an rvalue reference. The compiler will choose the vector’s move constructor instead of the copy constructor.
What the move constructor does:
- Directly “steals” a’s internal pointer and gives it to b.
- Sets a’s pointer to null to avoid releasing the same memory during destruction.
So in the end: b holds the data {1,2,3}. a becomes empty (size()==0, but is still a valid object)
Summary:
nums1 = std::move(vec);
- Old content is automatically released (done internally by move assignment)
- New content takes over
- vec becomes empty
No need to manually call the destructor.
