C++ Data Structures and Algorithms
eBook - ePub

C++ Data Structures and Algorithms

Wisnu Anggoro

Share book
  1. 322 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

C++ Data Structures and Algorithms

Wisnu Anggoro

Book details
Book preview
Table of contents
Citations

About This Book

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

Frequently asked questions

How do I cancel my subscription?
Simply head over to the account section in settings and click on “Cancel Subscription” - it’s as simple as that. After you cancel, your membership will stay active for the remainder of the time you’ve paid for. Learn more here.
Can/how do I download books?
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
What is the difference between the pricing plans?
Both plans give you full access to the library and all of Perlego’s features. The only differences are the price and subscription period: With the annual plan you’ll save around 30% compared to 12 months on the monthly plan.
What is Perlego?
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Do you support text-to-speech?
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Is C++ Data Structures and Algorithms an online PDF/ePUB?
Yes, you can access C++ Data Structures and Algorithms by Wisnu Anggoro in PDF and/or ePUB format, as well as other popular books in Computer Science & Programming in C++. We have over one million books available in our catalogue for you to explore.

Information

Year
2018
ISBN
9781788831970
Edition
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 of contents