Mark As Completed Discussion

In this section, we will apply the concepts we have learned in practical exercises. These exercises will help us reinforce our understanding of the STL library and its components in the context of engineering aspects related to finance and algorithmic trading.

Through these exercises, we will practice using various STL containers such as vectors, explore different algorithms provided by the STL, understand the concept of iterators, work with strings using the STL, and utilize the time library for time-related operations.

Let's start with an exercise that involves working with vectors.

Exercise 1: Vector Operations

Write a C++ program that performs the following operations on a vector of integers:

  1. Initialize a vector with the values {3, 8, 2, 5, 1}
  2. Print the elements of the vector
  3. Calculate and print the sum of all elements in the vector
  4. Add a new element to the vector with the value 4
  5. Print the updated elements of the vector

Remember to include the necessary headers and use appropriate syntax and functions from the STL.

TEXT/X-C++SRC
1#include <iostream>
2#include <vector>
3#include <numeric>
4
5int main() {
6    // Initialize a vector with values
7    std::vector<int> vec = {3, 8, 2, 5, 1};
8
9    // Print the elements of the vector
10    std::cout << "Vector elements: ";
11    for (int num : vec) {
12        std::cout << num << " ";
13    }
14
15    // Calculate the sum of all elements
16    int sum = std::accumulate(vec.begin(), vec.end(), 0);
17    std::cout << "\nSum of elements: " << sum << std::endl;
18
19    // Add a new element to the vector
20    int newElement = 4;
21    vec.push_back(newElement);
22
23    // Print the updated elements of the vector
24    std::cout << "Updated vector elements: ";
25    for (int num : vec) {
26        std::cout << num << " ";
27    }
28
29    return 0;
30}

In this exercise, we initialize a vector with the values {3, 8, 2, 5, 1} and perform the specified operations. We use the std::accumulate function from the <numeric> header to calculate the sum of all elements in the vector. Finally, we add a new element to the vector and print the updated elements.

Feel free to modify the exercise or explore additional concepts and functionalities of the STL library.

To further enhance your understanding and skills, try to solve the exercise on your own before referring to the provided solution. Good luck!