• Home
  • /
  • Blog
  • /
  • More Convenience Functions for Containers with C++20

September 24, 2020

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

 TimelineCpp20CoreLanguage

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

The erase-remove Idiom

Okay. Removing an element from a container is quite easy. In the 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 well-known trap 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 must 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 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 previously presented erase-remove idiom is quite lengthy (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 is 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 following convenience function contains.

Checking the Existence of an Element in an Associative Container

Thanks to the functions contains, you can quickly 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 lengthy. The same argumentation holds for the count call in line (2). The count call also has a performance issue. When you want to know if an element is in a container, 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.

 

// 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.

 

 

Leave a Reply


Your email address will not be published. Required fields are marked

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

Related Posts