Book Image

C++ Fundamentals

By : Antonio Mallia, Francesco Zoffoli
Book Image

C++ Fundamentals

By: Antonio Mallia, Francesco Zoffoli

Overview of this book

C++ Fundamentals begins by introducing you to the C++ compilation model and syntax. You will then study data types, variable declaration, scope, and control flow statements. With the help of this book, you'll be able to compile fully working C++ code and understand how variables, references, and pointers can be used to manipulate the state of the program. Next, you will explore functions and classes — the features that C++ offers to organize a program — and use them to solve more complex problems. You will also understand common pitfalls and modern best practices, especially the ones that diverge from the C++98 guidelines. As you advance through the chapters, you'll study the advantages of generic programming and write your own templates to make generic algorithms that work with any type. This C++ book will guide you in fully exploiting standard containers and algorithms, understanding how to pick the appropriate one for each problem. By the end of this book, you will not only be able to write efficient code but also be equipped to improve the readability, performance, and maintainability of your programs.
Table of Contents (9 chapters)
C++ Fundamentals
Preface

Lesson 5: Standard Library Containers and Algorithms


Activity 19: Storing User Accounts

  1. First, we include the header files for the array class and input/output operations with the required namespace:

    #include <array>
  2. An array of ten elements of type int is declared:

    array<int,10> balances;
  3. Initially, the values of the elements are undefined since it is an array of the fundamental data type int. The array is initialized using a for loop, where each element is initialized with its index. The operator size() is used to evaluate the size of the array and the subscript operator [ ] is used to access every position of the array:

    for (int i=0; i < balances.size(); ++i) 
    {
      balances[i] = 0;
    }
  4. We now want to update the value for the first and last user. We can use front() and back() to access the accounts of these users:

    balances.front() += 100;
    balances.back() += 100;

    We would like to store the account balance of an arbitrary number of users. We then want to add 100 users to the account list...