Menu
Coddy logo textTech

Modifying Algorithms

Lesson 21 of 23 in Coddy's C++ - Standard Template Library course.

In this lesson you will learn about modifying algorithms that are present in the C++ STL.
Modifying algorithms are designed to alter the value of the elements within a container.


We will be covering the following algorithms:

  • copy()
  • fill()
  • move()
  • swap()
  • reverse()

copy() method

The copy() method copies the elements from the range of two defined iterators into the range starting by the third iterator

vector<int> v1 = {1, 2, 3};
vector<int> v2;

copy(v1.begin(), v1.end(), v2.begin());

for(auto value : v1)
	cout << value << " ";
Output:
1 2 3

We used the copy() method to copy the content of the vector v1 to the vector v2.


fill() method

This method assigns every element in the given range defined by two iterators, with a given value.

vector<int> numbers(10); // creates an empty vector with 10 elements

fill(numbers.begin(), numbers.end(), 1);

for(auto value : numbers)
	cout << value << " ";

cout << endl;

fill(numbers.begin(), numbers.end() - 3, 2);

for(auto value : numbers)
	cout << value << " ";
Output:
1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 1 1 1

move() method

This method moves the elements from the current container and returns its rvalue.

vector<string> names;

string first = "John";
string second = "Max";

names.push_back(first);
names.push_back(move(second));

cout << first << endl;
cout << second << endl;
cout << names[1];
Output:
John

Max

As you can see, the move() method, empties the string, but returns it's value and the push_back() method insert the value in the vector.


swap() method

This method swaps the elements of two containers of the same type.

vector<int> v1 = {1, 2, 3};
vector<int> v2 = {4, 5, 6};

for(auto value : v1)
	cout << value << " ";
for(auto value : v2)
	cout << value << " ";

cout << endl;

swap(v1, v2);

for(auto value : v1)
	cout << value << " ";
for(auto value : v2)
	cout << value << " ";
Output:
1 2 3 4 5 6
4 5 6 1 2 3

reverse() method

This method reverses the order of the elements of one container, more precisely in the range of the two iterators.

vector<int> a = {1, 2, 3, 4, 5};

for(auto value : a)
	cout << value << " ";
	
cout << endl;
	
reverse(a.begin(), a.end());

for(auto value : a)
	cout << value << " ";
Output:
1 2 3 4 5
5 4 3 2 1

 

Try it yourself

This lesson doesn't include a code challenge.

All lessons in C++ - Standard Template Library