w3resource

C++ Exercises: Each element of a given list of integers is multiplied by five

C++ Basic Algorithm: Exercise-124 with Solution

Write a C++ program to create a new list from a given list of integers where each element is multiplied by 5.

Test Data:
({ 1, 2, 3}) -> {5, 10, 15}
({2, 4, 7, 8}) -> {10, 20, 35, 40})

Sample Solution:

C++ Code :

#include <bits/stdc++.h>
#include <list>

using namespace std;

list<int> test(list<int> nums) {
	       list<int> new_list;
	       list<int>::iterator it;
           for (it = nums.begin(); it != nums.end(); ++it)
            {
                new_list.push_back(*it*5);                
            }

            return new_list;
}

display_list(list<int> g)
{
    list<int>::iterator it;
    for (it = g.begin(); it != g.end(); ++it)
        cout << *it << ' ';
    cout << '\n';
}

int main() {

  list<int> nums = {1,2,3,4,5,6,7,8,9};
  cout << "Original list of elements:\n";
  display_list(nums);
  list<int> result_list;
  result_list = test(nums);
  cout << "\nNew list from the said list where each element is multiplied by 5:\n";
  display_list(result_list);
  return 0;
}

Sample Output:

Original list of elements:
1 2 3 4 5 6 7 8 9

New list from the said list where each element is multiplied by 5:
5 10 15 20 25 30 35 40 45

Flowchart:

Flowchart: Each element of a given list of integers is multiplied by five.

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Create an array of odd numbers and specific lengths from an array.
Next: Multiply each integer in a list three times.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.

C++ Programming: Tips of the Day

What is the usefulness of `enable_shared_from_this?

It enables you to get a valid shared_ptr instance to this, when all you have is this. Without it, you would have no way of getting a shared_ptr to this, unless you already had one as a member.

class Y: public enable_shared_from_this
{
public:

    shared_ptr f()
    {
        return shared_from_this();
    }
}

int main()
{
    shared_ptr p(new Y);
    shared_ptr q = p->f();
    assert(p == q);
    assert(!(p < q || q < p)); // p and q must share ownership
}

The method f() returns a valid shared_ptr, even though it had no member instance. Note that you cannot simply do this:

class Y: public enable_shared_from_this
{
public:

    shared_ptr f()
    {
        return shared_ptr(this);
    }
}

The shared pointer that this returned will have a different reference count from the "proper" one, and one of them will end up losing and holding a dangling reference when the object is deleted.

Ref : https://bit.ly/3pwVzzz