I would like to loop through an std::map
and delete items based on their contents. How best would this be done?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
edit: seems that this works in MSVC only
edit2: in c++0x this works for associative containers too
This is one simple way:
If you have a C++11-compliant compiler, here's an easy way to do this:
The idea is to walk the iterator forward from the start of the container to the end, checking at each step whether the current key/value pair should be deleted. If so, we remove the element iterated over using the
erase
member function, which then returns an iterator to the next element in the map. Otherwise, we advance the iterator forward normally.If you do not have a C++11-compliant compiler, or you're working with an older codebase, things are a bit trickier. Before C++11, the
erase
member function would not return an iterator to the next element in the map. This meant that in order to remove an element while iterating, you'd need to use a three-part dance:erase
on the copy of the old iterator.This is shown here:
This process was required because if you just called
erase
on the iterator, you'd invalidate it, meaning that operations like increment and decrement would lead to undefined behavior. The above code gets around this by setting up a copy of the iterator, advancingitr
so that it's at the next element, then erasing the temporary copy of the iterator.Using some Clever Trickiness, it's possible to shrink this code down at the expense of readability. The following pattern is common in older C++ code, but isn't necessary in C++11:
The use of the post-increment operator here is a clever way of making a copy of the old iterator (remember that a postfix ++ operator returns a copy of the original iterator value) while also advancing the older iterator.