C++ Data Structures and Algorithms
eBook - ePub

C++ Data Structures and Algorithms

Wisnu Anggoro

Compartir libro
  1. 322 páginas
  2. English
  3. ePUB (apto para móviles)
  4. Disponible en iOS y Android
eBook - ePub

C++ Data Structures and Algorithms

Wisnu Anggoro

Detalles del libro
Vista previa del libro
Índice
Citas

Información del 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++.

Preguntas frecuentes

¿Cómo cancelo mi suscripción?
Simplemente, dirígete a la sección ajustes de la cuenta y haz clic en «Cancelar suscripción». Así de sencillo. Después de cancelar tu suscripción, esta permanecerá activa el tiempo restante que hayas pagado. Obtén más información aquí.
¿Cómo descargo los libros?
Por el momento, todos nuestros libros ePub adaptables a dispositivos móviles se pueden descargar a través de la aplicación. La mayor parte de nuestros PDF también se puede descargar y ya estamos trabajando para que el resto también sea descargable. Obtén más información aquí.
¿En qué se diferencian los planes de precios?
Ambos planes te permiten acceder por completo a la biblioteca y a todas las funciones de Perlego. Las únicas diferencias son el precio y el período de suscripción: con el plan anual ahorrarás en torno a un 30 % en comparación con 12 meses de un plan mensual.
¿Qué es Perlego?
Somos un servicio de suscripción de libros de texto en línea que te permite acceder a toda una biblioteca en línea por menos de lo que cuesta un libro al mes. Con más de un millón de libros sobre más de 1000 categorías, ¡tenemos todo lo que necesitas! Obtén más información aquí.
¿Perlego ofrece la función de texto a voz?
Busca el símbolo de lectura en voz alta en tu próximo libro para ver si puedes escucharlo. La herramienta de lectura en voz alta lee el texto en voz alta por ti, resaltando el texto a medida que se lee. Puedes pausarla, acelerarla y ralentizarla. Obtén más información aquí.
¿Es C++ Data Structures and Algorithms un PDF/ePUB en línea?
Sí, puedes acceder a C++ Data Structures and Algorithms de Wisnu Anggoro en formato PDF o ePUB, así como a otros libros populares de Computer Science y Programming in C++. Tenemos más de un millón de libros disponibles en nuestro catálogo para que explores.

Información

Año
2018
ISBN
9781788831970
Edición
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...

Índice