Table of Contents
❌ Error example: Iterator is still incremented after deletion
? A simpler way: use remove_if erase (recommended for conditional deletion)
? Summary: Comparison of three common solutions
? Tips: Use reverse iterators to avoid interference
✅ Conclusion
Home Backend Development C++ C erase from vector while iterating

C erase from vector while iterating

Aug 05, 2025 am 09:16 AM
c++ vector

If it is iterating when deleting elements, you must avoid using invalid iterators. ① The correct way is to use it = vec.erase(it), and use the valid iterator returned by erase to continue traversing; ② Recommended "erase-remove" idiom for batch deletion: vec.erase(std::remove_if(vec.begin(), vec.end(), condition), vec.end()), which is safe and efficient; ③ You can use a reverse iterator to delete from back to front, the logic is clear, but you need to pay attention to the direction of the condition. Conclusion: Always update the iterator with the erase return value, prohibiting operations on the failed iterator, otherwise undefined behavior will result.

C erase from vector while iterating

In C, if you are iterating when deleting an element from std::vector , you need to be careful, because erase() will invalidate all iterators after the deleted element . If handled improperly, undefined behavior (such as crashing or skipping elements).

C erase from vector while iterating

But correctly using the return value of erase() can safely delete elements while traversing.


✅ Correct way: Use the iterator returned by erase()

std::vector::erase() returns an iterator pointing to the elements after the deleted element . We can take advantage of this feature to avoid using failed iterators.

C erase from vector while iterating
 #include <vector>
#include <iostream>

std::vector<int> vec = {1, 2, 3, 4, 5};

for (auto it = vec.begin(); it != vec.end(); ) {
    if (*it == 3) {
        it = vec.erase(it); // erase returns the next valid iterator} else {
          it;
    }
}

✅ This is a standard, safe and recommended approach.


❌ Error example: Iterator is still incremented after deletion

 for (auto it = vec.begin(); it != vec.end(); it) {
    if (*it == 3) {
        vec.erase(it); // Error! it expires, and then undefined behavior}
}

This can cause program crashes or unpredictable behavior.

C erase from vector while iterating

If you want to delete multiple elements according to conditions, it is recommended to use the "erase-remove" idiom :

 vec.erase(
    std::remove_if(vec.begin(), vec.end(), [](int n) {
        return n == 3; // Delete all elements equal to 3}),
    vec.end()
);

✅ Efficient, safe, clear code, suitable for scenarios where complex logic is not required to be executed when deleting.


? Summary: Comparison of three common solutions

method Applicable scenarios Recommended Things to note
erase() returns the iterator When deleting, you need to judge complex conditions or perform other operations. ✅ Recommended The return value must be received correctly, and do not Deleted it
erase-remove idiom Simple condition batch deletion ✅ Highly recommended The code is simpler and the performance is better
Reverse iterator rbegin/rend Delete from behind to front, some logic is more intuitive ✅ Available Pay attention to the logical direction of the condition

? Tips: Use reverse iterators to avoid interference

If you want to delete from behind, you can also use a reverse iterator to avoid affecting the previous index:

 for (auto it = vec.rbegin(); it != vec.rend(); ) {
    if (*it == 3) {
        it = vec.erase(it); // erase also returns the next one on reverse_iterator} else {
          it;
    }
}

Note: erase behavior on reverse_iterator is normal, but be careful whether the logic needs reverse processing.


✅ Conclusion

  • Iterate when deletion : use it = vec.erase(it) , don't Failed iterator.
  • Batch conditional removal : Use remove_if erase first.
  • Avoid using it after erase , otherwise it is undefined behavior.

Basically all is it, not complicated but it is easy to ignore details.

The above is the detailed content of C erase from vector while iterating. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1503
276
C   fold expressions example C fold expressions example Jul 28, 2025 am 02:37 AM

C folderexpressions is a feature introduced by C 17 to simplify recursive operations in variadic parameter templates. 1. Left fold (args...) sum from left to right, such as sum(1,2,3,4,5) returns 15; 2. Logical and (args&&...) determine whether all parameters are true, and empty packets return true; 3. Use (std::cout

C   char array to string example C char array to string example Aug 02, 2025 am 05:52 AM

The answer is: Use the std::string constructor to convert the char array to std::string. If the array contains the intermediate '\0', the length must be specified. 1. For C-style strings ending with '\0', use std::stringstr(charArray); to complete the conversion; 2. If the char array contains the middle '\0' but needs to convert the first N characters, use std::stringstr(charArray,length); to clearly specify the length; 3. When processing a fixed-size array, make sure it ends with '\0' and then convert it; 4. Use str.assign(charArray,charArray strl

C   find in vector example C find in vector example Aug 02, 2025 am 08:40 AM

The most common method of finding vector elements in C is to use std::find. 1. Use std::find to search with the iterator range and target value. By comparing whether the returned iterator is equal to end(), we can judge whether it is found; 2. For custom types or complex conditions, std::find_if should be used and predicate functions or lambda expressions should be passed; 3. When searching for standard types such as strings, you can directly pass the target string; 4. The complexity of each search is O(n), which is suitable for small-scale data. For frequent searches, you should consider using std::set or std::unordered_set. This method is simple, effective and widely applicable to various search scenarios.

C   endianness check example C endianness check example Jul 30, 2025 am 02:30 AM

The system endianness can be detected by a variety of methods, the most commonly used is the union or pointer method. 1. Use a union: Assign uint32_t to 0x01020304, if the lowest address byte is 0x04, it is a small endian, and if it is 0x01, it is a big endian; 2. Use pointer conversion: Assign uint16_t to 0x0102, read the byte order through the uint8_t pointer, [0]==0x02 and [1]==0x01 is a small endian, otherwise it is a big endian; 3. Compilation-time detection: define the constexpr function to determine whether the (char)&int variable is 1, and combine ifconstexpr to determine the endian order during the compilation period; 4. Runtime macro encapsulation: use (char*)&amp

What are the correct launch.json settings for debugging a C   application with GDB on Linux? What are the correct launch.json settings for debugging a C application with GDB on Linux? Aug 04, 2025 am 03:46 AM

TodebugaC applicationusingGDBinVisualStudioCode,configurethelaunch.jsonfilecorrectly;keysettingsincludespecifyingtheexecutablepathwith"program",setting"MIMode"to"gdb"and"type"to"cppdbg",using"ex

C   mutex example C mutex example Aug 03, 2025 am 08:43 AM

std::mutex is used to protect shared resources to prevent data competition. In the example, the automatic locking and unlocking of std::lock_guard is used to ensure multi-thread safety; 1. Using std::mutex and std::lock_guard can avoid the abnormal risks brought by manual management of locks; 2. Shared variables such as counters must be protected with mutex when modifying multi-threads; 3. RAII-style lock management is recommended to ensure exception safety; 4. Avoid deadlocks and multiple locks in a fixed order; 5. Any scenario of multi-thread access to shared resources should use mutex synchronization, and the final program correctly outputs Expected:10000 and Actual:10000.

How to compile and run C   in Sublime Text How to compile and run C in Sublime Text Jul 28, 2025 am 03:51 AM

Install the g compiler (Windows uses MinGW-w64, macOS runs xcode-select--install, and Linux executes sudoaptinstallbuild-essential); 2. Create a C.sublime-build file in SublimeText and fill in the specified JSON configuration; 3. After opening the .cpp file, press Ctrl B to compile, press Ctrl Shift B to select Run to compile and run, and the output results will be displayed in the bottom panel.

C   Boost library example C Boost library example Jul 30, 2025 am 01:20 AM

Install the Boost library, 2. Write code for DNS resolution using Boost.Asio, 3. Compile and link the boost_system library, 4. Run the program to output the IP address parsed by www.google.com; this example shows how Boost.Asio simplifies network programming in C, implements cross-platform, type-safe synchronous DNS queries through io_context and tcp::resolver, and supports IPv4 and IPv6 address resolution, and finally prints all resolution results.

See all articles