More Convenience Functions for Containers with C++20

Contents[Show]

Removing elements from a container or asking if an associative container has a specific key, is too complicated. I should say was because with C++20 the story changes.

 TimelineCpp20CoreLanguage

Let me start simple. You want to erase an element from a container. 

The erase-remove Idiom

Okay. Removing an element from a container is quite easy. In case of a std::vector you can use the function std::remove. 

 

// removeElements.cpp

#include <algorithm>
#include <iostream>
#include <vector>

int main() {

    std::cout << std::endl;

    std::vector myVec{-2, 3, -5, 10, 3, 0, -5 };

    for (auto ele: myVec) std::cout << ele << " ";
    std::cout << "\n\n";

    std::remove_if(myVec.begin(), myVec.end(), [](int ele){ return ele < 0; }); // (1)
    for (auto ele: myVec) std::cout << ele << " ";

    std::cout << "\n\n";

}

 

The program removeElemtens.cpp removes all elements the std::vector that is smaller than zero. Easy, or? Now, you fall into the trap that is well-known to each professional  C++ programmer. 

eraseRemove

std::remove or std::remove_if  inline (1) does not remove anything. The std::vector still has the same number of arguments. Both algorithms return the new logical end of the modified container. 

To modify a container, you have to apply the new logical end to the container.

 

// eraseRemoveElements.cpp

#include <algorithm>
#include <iostream>
#include <vector>

int main() {

    std::cout << std::endl;

    std::vector myVec{-2, 3, -5, 10, 3, 0, -5 };

    for (auto ele: myVec) std::cout << ele << " ";
    std::cout << "\n\n";

    auto newEnd = std::remove_if(myVec.begin(), myVec.end(),        // (1)
[](int ele){ return ele < 0; }); myVec.erase(newEnd, myVec.end()); // (2) // myVec.erase(std::remove_if(myVec.begin(), myVec.end(), // (3)
[](int ele){ return ele < 0; }), myVec.end());
for (auto ele: myVec) std::cout << ele << " "; std::cout << "\n\n"; }

 

Line (1) returns the new logical end newEnd of the container myVec. This new logical end is applied in the line (2) to remove all elements from myVec starting at newEnd. When you apply the functions remove and erase in one expression such as in line (3), you exactly see, why this construct is called erase-remove-idiom.

eraseRemoveElements

Thanks to the new functions erase and erase_if in C++20, erasing elements from containers is way more convenient.

erase and erase_if in C++20

With erase and erase_if, you can directly operate on the container. In contrast, the previous presented erase-remove idiom is quite verbose (line 3 in eraseRemoveElements.cpp): erase requires two iterators which I provided by the algorithm std::remove_if.

Let's see what the new functions erase and erase_if mean in practice. The following program erases elements for a few containers.

 

// eraseCpp20.cpp

#include <iostream>
#include <numeric>
#include <deque>
#include <list>
#include <string>
#include <vector>

template <typename Cont>                                         // (7)
void eraseVal(Cont& cont, int val) {
    std::erase(cont, val);
}

template <typename Cont, typename Pred>                          // (8)
void erasePredicate(Cont& cont, Pred pred) {
    std::erase_if(cont, pred);
}

template <typename Cont>
void printContainer(Cont& cont) {
    for (auto c: cont) std::cout << c << " ";
    std::cout << std::endl;
}

template <typename Cont>                                         // (6)
void doAll(Cont& cont) {
    printContainer(cont);
    eraseVal(cont, 5);
    printContainer(cont);
    erasePredicate(cont, [](auto i) { return i >= 3; } );
    printContainer(cont);
}

int main() {

    std::cout << std::endl;
    
    std::string str{"A Sentence with an E."};
    std::cout << "str: " << str << std::endl;
    std::erase(str, 'e');                                        // (1)
    std::cout << "str: " << str << std::endl;
    std::erase_if( str, [](char c){ return std::isupper(c); });  // (2)
    std::cout << "str: " << str << std::endl;
    
    std::cout << "\nstd::vector " << std::endl;
    std::vector vec{1, 2, 3, 4, 5, 6, 7, 8, 9};                  // (3)
    doAll(vec);
    
    std::cout << "\nstd::deque " << std::endl;
    std::deque deq{1, 2, 3, 4, 5, 6, 7, 8, 9};                   // (4)
    doAll(deq);
    
    std::cout << "\nstd::list" << std::endl;
    std::list lst{1, 2, 3, 4, 5, 6, 7, 8, 9};                    // (5)
    doAll(lst);
    
}

 

Line (1) erases all character e from the given string str. Line (2) applies the lambda expression to the same string and erases all upper case letters.

In the remaining program, elements of the sequence containers std::vector (line 3), std::deque (line 4), and std::list (line 5) are erased. On each container, the function template doAll (line 6) is applied. doAll erases the element 5 and all elements greater than 3. The function template erase (line 7) uses the new function erase and the function template erasePredicate (line 8) uses the new function erase_if.

Thanks to the Microsoft Compiler, here it the output of the program.

eraseCpp20

The new functions erase and erase_if can be applied to all containers of the Standard Template Library. This does not hold for the next convenience function contains.

Checking the Existence of an Element in an Associative Container

Thanks to the functions contains, you can easily check if an element exists in an associative container.

Stopp, you may say, we can already do this with find or count. 

No, both functions are not beginners friendly and have their downsides.

// checkExistens.cpp

#include <set>
#include <iostream>

int main() {

    std::cout << std::endl;

    std::set mySet{3, 2, 1};
    if (mySet.find(2) != mySet.end()) {    // (1)
        std::cout << "2 inside" << std::endl;
    }

    std::multiset myMultiSet{3, 2, 1, 2};
    if (myMultiSet.count(2)) {            // (2)
        std::cout << "2 inside" << std::endl;
    } 

    std::cout << std::endl;

}

 

The functions produce the expected result.

checkExistens

Here are the issues with both calls. The find call inline (1) is too verbose. The same argumentation holds for the count call in line (2). The count call has also a performance issue. When you want to know if an element is in a container, you should stop when you found it and not count until the end. In the concrete case myMultiSet.count(2) returned 2.

On the contrary, the contains member function in C++20 is quite convenient to use.

 

// containsElement.cpp

#include <iostream>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>

template <typename AssozCont>
bool containsElement5(const AssozCont& assozCont) {  // (1)
    return assozCont.contains(5);
}

int main() {
    
    std::cout << std::boolalpha;
    
    std::cout << std::endl;
    
    std::set<int> mySet{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    std::cout << "containsElement5(mySet): " << containsElement5(mySet);
    
    std::cout << std::endl;
    
    std::unordered_set<int> myUnordSet{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    std::cout << "containsElement5(myUnordSet): " << containsElement5(myUnordSet);
    
    std::cout << std::endl;
    
    std::map<int, std::string> myMap{ {1, "red"}, {2, "blue"}, {3, "green"} };
    std::cout << "containsElement5(myMap): " << containsElement5(myMap);
    
    std::cout << std::endl;
    
    std::unordered_map<int, std::string> myUnordMap{ {1, "red"}, {2, "blue"}, {3, "green"} };
    std::cout << "containsElement5(myUnordMap): " << containsElement5(myUnordMap);
    
    std::cout << std::endl;
    
}

 

There is not much to add to this example. The function template containsElement5 returns true if the associative container contains the key 5. In my example, I only used the associative containers std::set, std::unordered_set, std::map, and std::unordered_set which can not have a key more than once.

containsElement

What's next?

The convenience functions go on in my next post. With C++20, you can calculate the midpoint of two values, check if a std::string start or ends with a substring, and create callables with std::bind_front.

 

 

Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, Marko, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, espkk, Louis St-Amour, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Neil Wang, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Tobi Heideman, Daniel Hufschläger, Red Trip, Alexander Schwarz, Tornike Porchxidze, Alessandro Pezzato, Evangelos Denaxas, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Satish Vangipuram, and Michael Dunsky.

 

Thanks in particular to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, and Said Mert Turkal.

 

 

My special thanks to Embarcadero CBUIDER STUDIO FINAL ICONS 1024 Small

 

Seminars

I'm happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

Bookable (Online)

German

Standard Seminars (English/German)

Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.

New

Contact Me

Modernes C++,

RainerGrimmSmall

Comments   

0 #1 Marius 2020-09-29 06:35
if `remove_if` does not remove anything, then what happened to `-2`? and another `-5` ?
looks like the container is not in a well defined state.
Quote
+3 #2 Martin 2020-10-08 15:03
@ Marius

remove_if does not realy remove the matched elements but moves them to the end of the container and returns a new end iterator which is pointing to the first removed element. The container is reordered but in a well defined state.
This is can be more efficient than erasing because no heap operations are involved.
Quote

My Newest E-Books

Course: Modern C++ Concurrency in Practice

Course: C++ Standard Library including C++14 & C++17

Course: Embedded Programming with Modern C++

Course: Generic Programming (Templates)

Course: C++ Fundamentals for Professionals

Interactive Course: The All-in-One Guide to C++20

Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code

Visitors

Today 7204

Yesterday 7224

Week 29203

Month 34468

All 6892677

Currently are 159 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments