C++ Data Structures and Algorithms
eBook - ePub

C++ Data Structures and Algorithms

Wisnu Anggoro

Condividi libro
  1. 322 pagine
  2. English
  3. ePUB (disponibile sull'app)
  4. Disponibile su iOS e Android
eBook - ePub

C++ Data Structures and Algorithms

Wisnu Anggoro

Dettagli del libro
Anteprima del libro
Indice dei contenuti
Citazioni

Informazioni sul libro

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

Domande frequenti

Come faccio ad annullare l'abbonamento?
È semplicissimo: basta accedere alla sezione Account nelle Impostazioni e cliccare su "Annulla abbonamento". Dopo la cancellazione, l'abbonamento rimarrà attivo per il periodo rimanente già pagato. Per maggiori informazioni, clicca qui
È possibile scaricare libri? Se sì, come?
Al momento è possibile scaricare tramite l'app tutti i nostri libri ePub mobile-friendly. Anche la maggior parte dei nostri PDF è scaricabile e stiamo lavorando per rendere disponibile quanto prima il download di tutti gli altri file. Per maggiori informazioni, clicca qui
Che differenza c'è tra i piani?
Entrambi i piani ti danno accesso illimitato alla libreria e a tutte le funzionalità di Perlego. Le uniche differenze sono il prezzo e il periodo di abbonamento: con il piano annuale risparmierai circa il 30% rispetto a 12 rate con quello mensile.
Cos'è Perlego?
Perlego è un servizio di abbonamento a testi accademici, che ti permette di accedere a un'intera libreria online a un prezzo inferiore rispetto a quello che pagheresti per acquistare un singolo libro al mese. Con oltre 1 milione di testi suddivisi in più di 1.000 categorie, troverai sicuramente ciò che fa per te! Per maggiori informazioni, clicca qui.
Perlego supporta la sintesi vocale?
Cerca l'icona Sintesi vocale nel prossimo libro che leggerai per verificare se è possibile riprodurre l'audio. Questo strumento permette di leggere il testo a voce alta, evidenziandolo man mano che la lettura procede. Puoi aumentare o diminuire la velocità della sintesi vocale, oppure sospendere la riproduzione. Per maggiori informazioni, clicca qui.
C++ Data Structures and Algorithms è disponibile online in formato PDF/ePub?
Sì, puoi accedere a C++ Data Structures and Algorithms di Wisnu Anggoro in formato PDF e/o ePub, così come ad altri libri molto apprezzati nelle sezioni relative a Computer Science e Programming in C++. Scopri oltre 1 milione di libri disponibili nel nostro catalogo.

Informazioni

Anno
2018
ISBN
9781788831970
Edizione
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...

Indice dei contenuti