C++ Data Structures and Algorithms
eBook - ePub

C++ Data Structures and Algorithms

Wisnu Anggoro

Partager le livre
  1. 322 pages
  2. English
  3. ePUB (adapté aux mobiles)
  4. Disponible sur iOS et Android
eBook - ePub

C++ Data Structures and Algorithms

Wisnu Anggoro

DĂ©tails du livre
Aperçu du livre
Table des matiĂšres
Citations

À propos de ce livre

Learn how to build efficient, secure and robust code in C++ by using data structures and algorithms - the building blocks of C++About This Book‱ Use data structures such as arrays, stacks, trees, lists, and graphs with real-world examples‱ Learn the functional and reactive implementations of the traditional data structures‱ Explore illustrations to present data structures and algorithms, as well as their analysis, in a clear, visual mannerWho This Book Is ForThis book is for developers who would like to learn the Data Structures and Algorithms in C++. Basic C++ programming knowledge is expected.What You Will Learn‱ Know how to use arrays and lists to get better results in complex scenarios‱ Build enhanced applications by using hashtables, dictionaries, and sets‱ Implement searching algorithms such as linear search, binary search, jump search, exponential search, and more‱ Have a positive impact on the efficiency of applications with tree traversal‱ Explore the design used in sorting algorithms like Heap sort, Quick sort, Merge sort and Radix sort‱ Implement various common algorithms in string data types‱ Find out how to design an algorithm for a specific task using the common algorithm paradigmsIn DetailC++ is a general-purpose programming language which has evolved over the years and is used to develop software for many different sectors. This book will be your companion as it takes you through implementing classic data structures and algorithms to help you get up and running as a confident C++ programmer.We begin with an introduction to C++ data structures and algorithms while also covering essential language constructs. Next, we will see how to store data using linked lists, arrays, stacks, and queues. Then, we will learn how to implement different sorting algorithms, such as quick sort and heap sort. Along with these, we will dive into searching algorithms such as linear search, binary search and more. Our next mission will be to attain high performance by implementing algorithms to string datatypes and implementing hash structures in algorithm design. We'll also analyze Brute Force algorithms, Greedy algorithms, and more.By the end of the book, you'll know how to build components that are easy to understand, debug, and use in different applications.Style and approachReaders will be taken through an indispensable list of data structures and algorithms so they can confidently begin coding in C++.

Foire aux questions

Comment puis-je résilier mon abonnement ?
Il vous suffit de vous rendre dans la section compte dans paramĂštres et de cliquer sur « RĂ©silier l’abonnement ». C’est aussi simple que cela ! Une fois que vous aurez rĂ©siliĂ© votre abonnement, il restera actif pour le reste de la pĂ©riode pour laquelle vous avez payĂ©. DĂ©couvrez-en plus ici.
Puis-je / comment puis-je télécharger des livres ?
Pour le moment, tous nos livres en format ePub adaptĂ©s aux mobiles peuvent ĂȘtre tĂ©lĂ©chargĂ©s via l’application. La plupart de nos PDF sont Ă©galement disponibles en tĂ©lĂ©chargement et les autres seront tĂ©lĂ©chargeables trĂšs prochainement. DĂ©couvrez-en plus ici.
Quelle est la différence entre les formules tarifaires ?
Les deux abonnements vous donnent un accĂšs complet Ă  la bibliothĂšque et Ă  toutes les fonctionnalitĂ©s de Perlego. Les seules diffĂ©rences sont les tarifs ainsi que la pĂ©riode d’abonnement : avec l’abonnement annuel, vous Ă©conomiserez environ 30 % par rapport Ă  12 mois d’abonnement mensuel.
Qu’est-ce que Perlego ?
Nous sommes un service d’abonnement Ă  des ouvrages universitaires en ligne, oĂč vous pouvez accĂ©der Ă  toute une bibliothĂšque pour un prix infĂ©rieur Ă  celui d’un seul livre par mois. Avec plus d’un million de livres sur plus de 1 000 sujets, nous avons ce qu’il vous faut ! DĂ©couvrez-en plus ici.
Prenez-vous en charge la synthÚse vocale ?
Recherchez le symbole Écouter sur votre prochain livre pour voir si vous pouvez l’écouter. L’outil Écouter lit le texte Ă  haute voix pour vous, en surlignant le passage qui est en cours de lecture. Vous pouvez le mettre sur pause, l’accĂ©lĂ©rer ou le ralentir. DĂ©couvrez-en plus ici.
Est-ce que C++ Data Structures and Algorithms est un PDF/ePUB en ligne ?
Oui, vous pouvez accĂ©der Ă  C++ Data Structures and Algorithms par Wisnu Anggoro en format PDF et/ou ePUB ainsi qu’à d’autres livres populaires dans Computer Science et Programming in C++. Nous disposons de plus d’un million d’ouvrages Ă  dĂ©couvrir dans notre catalogue.

Informations

Année
2018
ISBN
9781788831970
Édition
1

Storing Data in Lists and Linked Lists

In the previous chapter, we discussed basic C++ programming, so that now we can build a program and run it. We also tried to find out the complexity of the code flow using algorithm analysis. In this chapter, we are going to learn about building the list and linked list data structures and find out the complexity of each data structure. To understand all of the concepts in these data structures, these are the topics we are going to discuss:
  • Understanding the array data type and how to use it
  • Building the list data structure using the array data type
  • Understanding the concept of node and node chaining
  • Building SinglyLinkedList and DoublyLinkedList using node chaining
  • Applying the Standard Template Library to implement the list and linked list

Technical requirements

To follow along with this chapter including the source code, we require the following:
  • A desktop PC or Notebook with Windows, Linux, or macOS
  • GNU GCC v5.4.0 or above
  • Code::Block IDE v17.12 (for Windows and Linux OS) or Code::Block IDE v13.12 (for macOS)
  • You will find the code files on GitHub at https://github.com/PacktPublishing/CPP-Data-Structures-and-Algorithms

Getting closer to an array

An array is a series of elements with the same data type that is placed in contiguous memory locations. This means that the memory allocation is assigned in consecutive memory blocks. Since it implements contiguous memory locations, the elements of the array can be individually accessed by the index. Let's take a look at the following array illustration:
As we can see in the preceding illustration, we have an array containing five elements. Since the array uses zero-based indexing, the index starts from 0. This index is used to access the element value and to also replace the element value. The memory address stated in the illustration is for example purposes only. In reality, the memory address might be different. However, it illustrates that the memory allocation is contiguous.
Now, if we want to create the preceding array in C++, here is the code:
// Project: Array.cbp
// File : Array.cpp

#include <iostream>

using namespace std;

int main()
{
// Initialize an array
int arr[] = { 21, 47, 87, 35, 92 };

// Access each element
cout << "Array elements: ";
for(int i = 0; i < sizeof(arr)/sizeof(*arr); ++i)
cout << arr[i] << " ";
cout << endl;

// Manipulate several elements
arr[2] = 30;
arr[3] = 64;

// Access each element again
cout << "Array elements: ";
for(int i = 0; i < sizeof(arr)/sizeof(*arr); ++i)
cout << arr[i] << " ";
cout << endl;

return 0;
}
From the preceding code, we see that initializing an array is simple, and this is done by defining the array data type, the array's name followed by a couple of square brackets ([]), and the element's value. In the preceding code, our array's name is arr. We can access each element by using the index. In the code, we print each element by iterating each element and accessing the element value using arr[i]. We also manipulate the value of indexes 2 and 3 by using arr[2] = 30 and arr[3] = 64. If we build and run the code, we will get the following result:
As we can see in the preceding screenshot, we've got what we expected since we have successfully initialized an array, accessed each element, and manipulated the element's value.
The array data type doesn't have a built-in method to find out how many elements the array has. Even though we already know that the number of elements is five, we use sizeof(arr)/sizeof(*arr) to figure out the number of elements. It's the best practice in array manipulation because, sometimes, we don't know how many elements the array has. However, this only works when the sizeof(arr)/sizeof(*arr) construct is in the same scope as the definition of the array. If, for example, we try this from a function that receives the array as a parameter, this will fail.
There's an interesting fact about arrays—we can access the array's element using a pointer. As you may know, a pointer is a variable that holds the address instead of the value. And, since we discussed earlier that each element in the array has its own address, we can access each array's element using its address.
To use a pointer as an array, we need to initialize it to hold an array, as shown in the following example:
int * ptr = new int[5] { 21, 47, 87, 35, 92 };
After the preceding initialization, we have a pointer named ptr that points to the first element of an array containing five elements. However, the ptr variable holds the first array's element address at the start. To access the next address, we can increment the ptr variable (ptr++) so that it will point to the next element. To get the value of the currently selected address, we can use a wildcard symbol before the pointer name (*ptr); see the following two lines of code:
cout << *ptr << endl;
cout << ptr << endl;
The former statement in the preceding code snippet will print out the value that the pointer points to, and the latter will print the address that the pointer holds. Interestingly, since we initialize the ptr pointer as an array, we can access the value of each element and the address as well by its index. Please take a look at the following code snippet:
cout << ptr[i] << endl;
cout << &ptr[i] << endl;
In the preceding code snippet, the former line will print the value of the selected element and the latter will print the address of the selected element (since we added the apostrophe symbol before the pointer name—&ptr[i]). Now, let's wrap them all to create a code, as follows:
// Project: Array_As_Pointer.cbp
// File : Array_As_Pointer.cpp

#include <iostream>

using namespace std;

int main()
{
// Initialize the array length
int arrLength = 5;

// Initialize a pointer
// to hold an array
int * ptr = new int[arrLength] { 21, 47, 87, 35, 92 };

// Display each element value
// by incrementing the pointer (ptr++)
cout << "Using pointer increment" << endl;
cout << "Value\tAddress" << endl;
while(*ptr)
{
cout << *ptr << "\t";
cout << ptr << endl;
ptr++;
}


// Since we have moved forward the pointer five tim...

Table des matiĂšres