How it works...

In the first recipe of this chapter, we created a custom container wrapper that mimics a std::vector, but which ensures that elements in the vector remain in sorted order at all times, including the addition of the std::vector::push_back() function and the std::vector::emplace_back() function. In this recipe, we will add the std::set::insert() and std::set::emplace() functions to our custom container.

Since our container wrapper always ensures that std::vector is in sorted order, there is no difference between adding an element to the front, back, or middle of the vector. No matter which position an element is added to the vector, it must be sorted prior to the vector being accessed, which means that the order in which the element is added will likely change regardless of which position it is added in.

This lack of concern for where an element is added is similar to that of std::set. The std::set adds elements to a set, and then later returns true or false, depending on whether the element being tested is a member of the set. The std::set provides the insert() and emplace() functions for adding elements to the set. Let's add these same APIs to our custom container, as follows:

    void insert(const T &value)
{
push_back(value);
}

void insert(T &&value)
{
push_back(std::move(value));
}

template<typename... Args>
void emplace(Args&&... args)
{
emplace_back(std::forward<Args>(args)...);
}

As you can see in the preceding code snippet, we have added an insert() function (both the copy and the move), as well as an emplace() function, which does nothing more than call their push_back() and emplace_back() equivalents, ensuring that the parameters passed to these functions are properly forwarded. The only difference between these APIs and the APIs that we added in the previous recipe, Using a simple wrapper around std::vector, is the name of the function itself.

Although such a change might seem trivial, this is important as it redefines the concept between the container's APIs with the user. The push_back() and emplace_back() functions suggest that the element is added to the back of the vector when, in fact, it is not. Instead, they are simply added to the std::vector, and the order of the std::vector is changed based on the value of the element added. For this reason, the push_back() and emplace_back() functions are needed, but should either be renamed or marked as private to ensure that the user only uses the insert() and emplace() versions to properly manage expectations. When writing your own containers (even for wrappers), it is important that you adhere to the principle of least surprise, which ensures that the APIs that a user is using will work the way that the APIs might suggest.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset