Creating and Implementing Your Own Container

In this chapter, you will learn how to create your own custom container in C++ by leveraging an existing container that the C++ Standard Template Library already provides. This chapter is important because, in a lot of cases, your code will have common operations that are performed on a Standard Template Library container that are duplicated throughout the code (as is the case with implementing thread safety). The recipes in this chapter will teach you how to easily encapsulate this duplicated code into a custom container without having to write your own container from scratch or littering your code with duplicated logic that is hard to test and validate.

Throughout this chapter, you will learn the skills needed to implement a custom wrapper container, capable of ensuring that std::vector is maintained in sorted order at all times. The first recipe will teach you the basics of how to create this wrapper. The second recipe will expand upon the first, teaching you how to redefine the interface of a container based on how the container operates. In this case, since the container is always in sorted order, you will learn why providing a push_back() function doesn't make sense, even though all we are doing is creating a wrapper (the addition of the wrapper changes the concept of the container itself). In the third recipe you will learn the skills to work with iterators and why, in this example, const iterators can only be supported. Finally, we will add several additional APIs to our container to provide a complete implementation.

The recipes in this chapter are as follows:

  • Using a simple wrapper around std::vector
  • Adding the relevant parts of the std::set API
  • Working with iterators
  • Adding the relevant parts of the std::vector API

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

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