C++ <vector> begin / end function
beginandendis the most important iterator function in vector, used toGet the beginning and ending iterators of the container。
beginandendare member functions of container classes:
beginreturns a pointer to the first element of the containerIteratorendreturns a position past the last element of the containerIterator(Sentinel iterator)
These two functions are the foundation of C++ standard library algorithms and range-based for loops.
Word Definitions: beginRepresents "begin",endRepresents "end".
Basic syntax and parameters
beginandendare member functions of container classes, and calling them requires no arguments.
Syntax format
iterator begin(); const_iterator begin() const; iterator end(); const_iterator end() const;
Parameter description
- Parameter: No parameters
- These functions do not accept any parameters.
Function description
- Return Value:
begin()Returns an iterator pointing to the first element.end()Returns an iterator (sentinel) pointing to the position after the last element.
- Effect: The returned iterator can be used to traverse the container or to work with algorithms.
- Note:
end()The returned iterator points to a "virtual" position; it cannot be dereferenced, only used for comparison.
Example
Let us thoroughly master through a series of examplesbeginandendUsage.
Example 1: Basic usage - traversing the container
Example
#include <vector>
int main() {
std::vector<int> numbers = {10, 20, 30, 40, 50};
// Traverse using an iterator
std::cout << "Traverse using an iterator: ";
for(auto it = numbers.begin(); it != numbers.end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
return 0;
}
Expected output:
使用迭代器遍历: 10 20 30 40 50
Code analysis:
numbers.begin()Returns an iterator pointing to the first element (10).numbers.end()Returns an iterator pointing to the position after the last element.- Loop condition
it != numbers.end()Ensures traversal of all elements.
Example 2: Range-based for loop
The range-based for loop introduced in C++11 essentially uses at its corebeginandend。
Example
#include <vector>
#include <string>
int main() {
std::vector<std::string> names = {"Alice", "Bob", "Charlie"};
// Range-based for loop (internally uses begin/end)
std::cout << "Use range-based for loop: ";
for(const auto& name : names) {
std::cout << name << " ";
}
std::cout << std::endl;
return 0;
}
Expected output:
使用范围 for 循环: Alice Bob Charlie
Code analysis:
- The range-based for loop is a concise way to use iterators.
- The compiler will automatically call
begin()andend()。
Example 3: Using STL algorithms
Standard library algorithms require iterators to specify ranges.
Example
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {5, 2, 8, 1, 9, 3};
// Sort
std::sort(numbers.begin(), numbers.end());
std::cout << "After sorting: ";
for(int n : numbers) {
std::cout << n << " ";
}
std::cout << std::endl;
// Find element
auto it = std::find(numbers.begin(), numbers.end(), 8);
if(it != numbers.end()) {
std::cout << "Found element: " << *it << std::endl;
}
return 0;
}
Expected output:
排序后: 1 2 3 5 8 9 找到元素: 8
Code analysis:
std::sort(begin, end)Use iterators to specify the sorting range.std::find(begin, end, value)Use iterators to specify the search range.
Example 4: Reverse iterators
UsagerbeginandrendCan traverse the container in reverse.
Example
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
// Forward traversal
std::cout << "Forward: ";
for(auto it = numbers.begin(); it != numbers.end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
// Reverse traversal (using rbegin/rend)
std::cout << "Reverse: ";
for(auto it = numbers.rbegin(); it != numbers.rend(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
return 0;
}
Expected output:
正向: 1 2 3 4 5 反向: 5 4 3 2 1
Code analysis:
rbegin()Returns a reverse iterator pointing to the last element.rend()Returns a reverse iterator pointing to the position before the first element.
Example 5: Iterator arithmetic operations
Iterators support arithmetic operations, allowing quick jumps to a specified position.
Example
#include <vector>
int main() {
std::vector<int> numbers = {10, 20, 30, 40, 50, 60, 70};
// Get the third element (index 2)
auto it = numbers.begin() + 2;
std::cout << "begin() + 2 = " << *it << std::endl;
// Calculate the distance between two iterators
auto first = numbers.begin();
auto last = numbers.end();
auto distance = last - first;
std::cout << "Container size (distance): " << distance << std::endl;
// Get the middle element
auto mid = numbers.begin() + (numbers.size() / 2);
std::cout << "Middle element: " << *mid << std::endl;
return 0;
}
Expected output:
begin() + 2 = 30 容器大小(距离): 7 中间元素: 40
Code analysis:
- Iterator support
+、-and other arithmetic operations. - You can use
end() - begin()Compute the size of the container.
Example 6: Conversion between iterators and indices
Iterators and indices can be converted to each other.
Example
#include <vector>
int main() {
std::vector<int> numbers = {10, 20, 30, 40, 50};
// Convert index to iterator
size_t index = 2;
auto it = numbers.begin() + index;
std::cout << "Index " << index << " corresponding element: " << *it << std::endl;
// Convert iterator to index
auto iter = numbers.begin() + 3;
size_t idx = iter - numbers.begin();
std::cout << "Index corresponding to iterator: " << idx << std::endl;
return 0;
}
Expected output:
索引 2 对应的元素: 30 迭代器对应的索引: 3
Code analysis:
begin() + indexConvert an index to an iterator.iter - begin()Convert an iterator to an index.
Example 7: Using iterators to modify elements
Iterators return references, which can be used to modify elements.
Example
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
std::cout << "Before modification: ";
for(int n : numbers) std::cout << n << " ";
std::cout << std::endl;
// Multiply all elements by 2 using iterators
for(auto it = numbers.begin(); it != numbers.end(); ++it) {
*it *= 2;
}
std::cout << "After modification: ";
for(int n : numbers) std::cout << n << " ";
std::cout << std::endl;
return 0;
}
Expected output:
修改前: 1 2 3 4 5 修改后: 2 4 6 8 10
Code analysis:
- Iterator dereference (
*it) returns a reference to the element. - You can directly modify this reference to change the element's value.
other extensions