Home > Article > Backend Development > How to replace elements in C++ STL container?
The method of replacing elements in an STL container is as follows: std::vector: use at() or [] operator; std::list: access elements through iterator; std::map and std::unordered_map: use [ ] operator.
In the C++ Standard Template Library (STL), there are various containers that can store and manipulate elements. Replacing an element at a specific location in a container is a common task. Here's how to replace elements in different STL container types:
1. Replace elements in std::vector
for std::vector
, specific elements can be accessed and modified using the at()
or []
operators.
// 使用 at() std::vector<int> vec{1, 2, 3, 4, 5}; vec.at(2) = 10; // 替换 vec[2] 为 10 // 使用 [] vec[3] = 20; // 替换 vec[3] 为 20
2. Replace elements in std::list
For std::list
, you can useiterator
Access and modify elements.
std::list<std::string> lst{"a", "b", "c", "d", "e"}; auto it = std::next(lst.begin(), 2); // 迭代器指向 lst[2] *it = "z"; // 替换 lst[2] 为 "z"
3. Replace elements in
std::map and
for std::map
and std::unordered_map
, you can use the []
operator to access and modify specific elements.
// std::map std::map<std::string, int> mp{ {"a", 1}, {"b", 2}, {"c", 3} }; mp["a"] = 10; // 替换 mp["a"] 为 10 // std::unordered_map std::unordered_map<std::string, int> ump{ {"a", 1}, {"b", 2}, {"c", 3} }; ump["a"] = 10; // 替换 ump["a"] 为 10
Practical case
Suppose we have a std::vector
, which stores the names of students, and we need to reorder them in alphabetical order Name. We can use STL's std::sort()
function to sort the container, and the at()
function to replace elements to match the sorted order.
std::vector<std::string> names{"John", "Alice", "Bob", "Mary", "David"}; std::sort(names.begin(), names.end()); for (int i = 0; i < names.size(); ++i) { names.at(i) = std::to_string(i + 1) + ". " + names[i]; }
In this example, we sort the names
container, then iterate through the elements one by one and replace them with the modified string, including the position and name. The end result is an alphabetical list of names, preceded by their rank.
The above is the detailed content of How to replace elements in C++ STL container?. For more information, please follow other related articles on the PHP Chinese website!