C++. Class vector. Methods that modify data in the array

Class vector. Methods that modify data in the array. Methods push_back(), pop_back(), clear(), swap(), operator=(), erase(), insert(), assign()

Before exploring this topic, it is recommended that you familiarize yourself with the following topic:


Contents


Search other resources:

1. Method push_back(). Add item to the end of the vector

The push_back() method is used to add an item to the end of the array. The method has 2 overloaded implementations, the declaration syntax of which is as follows

void vector<T>::push_back(T&& val)
void vector<T>::push_back(const T& val)

here T is the type of the elements of the vector.

Example.

...

// Method push_back() - add an element to the end of the vector.
// 1. Declare a vector of 10 elements of type long long.
vector<long long> A(10);

// 2. Fill the array with data
for (int i = 0; i < A.size(); i++)
  A[i] = i * i;

// 3. Add an item to the end of the array
A.push_back(10000L);

// 4. Get new length of array
int count = A.size(); // count = 11

...

 

2. Method pop_back(). Remove the last element of the vector

The pop_back() method is used to remove the last element of a dynamic array. The syntax for declaring a method is as follows

void vector<T>::pop_back()

here T – the type of the array elements.

Example.

...

// Method pop_back() - remove the last element from the array.
// 1. Declare a pointer to a vector of 5 float elements.
vector<float>* A = new vector<float>(5);

// 2. Fill the array with data
A->at(0) = 2.88f;
A->at(1) = 3.8f;
A->operator[](2) = 4.4f; // so it is also possible
A->at(3) = 4.9f;
A->at(4) = 5.5f;

// 3. Output the array to a string
for (int i = 0; i < A->size(); i++)
  cout << A->at(i) << " ";

// 4. Remove the last element
A->pop_back();

// 5. Get the new length of array
int count = A->size(); // count = 4

...

 

3. Method clear(). Removes all elements from the array.

The clear() method is designed to remove all elements from an array. The length of the array returned by the size() method becomes 0. The syntax for declaring the clear() method is as follows:

void vector<T>::clear()

here T – the type of the array elements.

Example.

...

// Method clear() - removes all elements from the array.
// 1. Declare a vector of 10 elements of type short.
vector<short> A(10);

// 2. Fill the array with data
for (int i = 0; i < A.size(); i++)
  A.at(i) = i;

// 3. Print the size of array
cout << A.size() << endl; // 10

// 4. Remove all elements from array
A.clear();

// 5. Re-print the size of the array
cout << A.size() << endl; // 0

...

 

4. Method swap(). Swapping two vectors

The swap() method is used to swap two vectors. The types of vectors must match. The general form of the method declaration is as follows

void vector<T>::swap(vector<T>& _Right)

here

  • T – the type of vector’s items;
  • _Right – an array to swap with the current array.

Example.

...

// Method swap() - swapping vectors

// 1. Declare two arrays
vector<short> A1;
vector<short> A2;

// 2. Fill the array with data
initializer_list<short> L1 = { 1, 2, 3, 4 };
initializer_list<short> L2 = { 5, 6, 7, 8, 9 };
A1.assign(L1); // A1 = { 1, 2, 3, 4 }
A2.assign(L2); // A2 = { 5, 6, 7, 8, 9 }

// 3. Swap two arrays
A1.swap(A2); // A1 = { 5, 6, 7, 8, 9 }, A2 = { 1, 2, 3, 4 }

...

 

5. Assigning arrays. Overloaded operator =

A dynamic array of vector type allows the operation of assigning one array to another using the overloaded = operator. In this case, an additional copy of another array is created. Thus, the arrays are located in different parts of the memory.

Example.

...

// Arrays assignment
// 1. Create array of integers based on initialization list
initializer_list<int> L = { 1, 2, 3, 4, 5 };
vector<int> A1(L); // A1 = { 1, 2, 3, 4, 5 }

// 2. Declare another empty array
vector<int> A2;

// 3. Assign one array to another
A2 = A1; // A2 = { 1, 2, 3, 4, 5 }

...

 

6. Method erase(). Remove an element or multiple elements of the specified range

The erase() method is used to remove elements from a dynamic array of vector type. The method has two overloaded implementations.

The first implementation has the following syntax:

vector<T>::iterator erase(vector<T>::const_iterator First, vector<T>::const_iterator Last)

here

  • T – the type of the array elements;
  • First – an iterator that points to the first element of the range to be removed;
  • Last – an iterator pointing to the item after the last item in the range to be removed.

This implementation of the erase() method returns an iterator pointing to the portion of the original array that begins with the Last iterator.

The second implementation has the syntax:

vector<T>::iterator erase(vector<T>::const_iterator Where)

here

  • T – type of array elements;
  • Where – an iterator pointing to the element in the array to be removed.

This implementation returns an iterator pointing to the beginning of the original array.

Example. The example provides a demo program that uses the erase() method.

#include <iostream>
#include <vector>
using namespace std;

void main()
{
  // 1. Create a vector of 10 integers
  vector<int> A(10);

  // 2. Fill vector with data: A = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
  for (int i = 0; i < A.size(); i++)
    A[i] = i;

  // 3. Print array A to screen
  cout << "A = ";
  for (int i = 0; i < A.size(); i++)
    cout << A[i] << " ";
  cout << endl;

  // 4. Remove items with indices 2 to 4 inclusive
  // 4.1. Declare 3 iterators
  vector<int>::iterator it1 = A.begin() + 2; // the iterator points to the element at index 2
  vector<int>::iterator it2 = A.begin() + 5; // the iterator points to the element at index 5
  vector<int>::iterator it3; // an iterator that will point to another chunk of array A

  // 4.2. Call the method erase() - delete a fragment
  it3 = A.erase(it1, it2); // A = [ 0, 1, 5, 6, 7, 8, 9 ]

  // 5. Display the result using the iterator it3.
  // The iterator points to a slice of the it3 array => [ 5, 6, 7, 8, 9 ]
  cout << "it3 => ";
  while (it3 != A.end())
  {
    cout << *it3 << " ";
    it3++;
  }
  cout << endl;

  // 6. Print array after deletion: A = [ 0, 1, 5, 6, 7, 8, 9 ]
  cout << "A = ";
  for (int i = 0; i < A.size(); i++)
    cout << A[i] << " ";
  cout << endl;

  // 7. Remove the first element in an array
  // 7.1. Declare an iterator on the first element of an array
  vector<int>::iterator it4 = A.begin();

  // 7.2. Call the erase() method with the single iterator parameter
  A.erase(it4);

  // 7.3. Print array A again
  cout << "A = ";
  for (int i = 0; i < A.size(); i++)
    cout << A[i] << " ";
  cout << endl;
}

Program execution result

A = 0 1 2 3 4 5 6 7 8 9
it3 => 5 6 7 8 9
A = 0 1 5 6 7 8 9
A = 1 5 6 7 8 9

 

7. Method insert(). Inserts an element or group of elements into a vector

The insert() method provides several ways to insert one or more elements into an array. Each flavor is defined by a separate overloaded method implementation.

7.1. Inserting an initialization list into a vector

With this method of insertion, the declaration of the insert() method is as follows:

vector<T>::iterator insert(
    vector<T>::const_iterator _Where,
    initializer_list _llist
)

here

  • T – the type of the array elements;
  • initializer_list – the type of the initialization list;
  • _Where – an iterator pointing to the insertion position;
  • _llist – the initialization list.

The method returns an iterator pointing to the beginning of the insert chunk.

Example.

#include <iostream>
#include <vector>
using namespace std;

void main()
{
  // Method insert() - inserting an initialization list into a vector

  // 1. Declare an array of 5 elements of type double
  vector<double> A(5);

  // 2. Fill an array with 1.0 numbers
  A.assign(5, 1.0); // A = { 1.0, 1.0, 1.0, 1.0, 1.0 }

  // 3. Insert initialization list at position 2
  // 3.1. Declare initialization list L
  initializer_list<double> L = { 2.2, 3.2 };

  // 3.2. Declare an iterator and point it to position 2
  vector<double>::iterator it = A.begin() + 2;

  // 3.3. Invoke the insert() method
  vector<double>::iterator it2;
  it2 = A.insert(it, L); // A = { 1, 1, 2.2, 3.2, 1, 1, 1 }

  // 4. Display the modified array A
  cout << "A = ";
  for (int i = 0; i < A.size(); i++)
    cout << A[i] << " ";
  cout << endl;

  // 5. Display data by iterator
  cout << "it2 => ";
  while (it2 != A.end())
  {
    cout << *it2 << " ";
    it2++;
  }
}

Program result

A = 1 1 2.2 3.2 1 1 1
it2 => 2.2 3.2 1 1 1

 

7.2. Inserting an element a specified number of times at a specified position

This implementation of the method allows you to insert an element at a given position a specified number of times.

vector<T>::iterator insert(
    vector<T>::const_iterator _Where,
    const size_t _Count,
    const T& Val
)

here

  • T – type of array elements;
  • _Where – an iterator pointing to the insertion position;
  • _Count – the number of Val elements to be inserted into the array;
  • Val – the item to insert into the array.

Example.

#include <iostream>
#include <vector>
using namespace std;

void main()
{
  // Method insert() - inserting an element the specified number of times

  // 1. Declare an array of 5 elements of type char
  vector<char> A(5);

  // 2. Fill the array with symbols: A = { '-', '-', '-', '-', '-' }
  for (int i = 0; i < A.size(); i++)
    A[i] = '-';

  // 3. Insert 4 '+' characters at position 3 of the array
  // 3.1. Declare an iterator at position 3
  vector<char>::iterator it = A.begin() + 3;

  // 3.2. Invoke method insert()
  vector<char>::iterator it2;
  it2 = A.insert(it, 4, '+');

  // 4. Display the resulting array
  cout << "A = ";
  for (int i = 0; i < A.size(); i++)
    cout << A[i] << " ";
  cout << endl;

  // 5. Print the fragment pointed to by iterator it2
  cout << "it2 => ";
  while (it2 != A.end())
  {
    cout << *it2 << " ";
    it2++;
  }
}

Program result

A = - - - + + + + - -
it2 => + + + + - -

 

7.3. Inserting a single element at a given position

To insert a single element at the position pointed to by the iterator, use one of the following forms of the insert() method

vector<T>::iterator insert(vector<T>::const_iterator _Where, T&& _Val)
vector<T>::iterator insert(vector<T>::const_iterator _Where, const T& _Val)

here

  • T – the type of the array elements;
  • _Where – an iterator pointing to the insertion position;
  • _Val – the value to be inserted.

This form of the function returns an iterator pointing to the insertion position.

Example.

#include <iostream>
#include <vector>
using namespace std;

void main()
{
  // insert() method - inserting a single element at a given position

  // 1. Declare an array of 5 elements of type short
  vector<short> A(5);

  // 2. Fill an array with numbers based on an initialization list
  initializer_list<short> L = { 1, 2, 3, 4, 5 };
  A.assign(L);

  // 3. Insert number 100 into position 0
  // 3.1. Declare an iterator that points to position 0
  vector<short>::iterator it = A.begin();

  // 3.2. Invoke the insert() method
  vector<short>::iterator it2 = A.insert(it, 100);

  // 4. Print the resulting array
  cout << "A = ";
  for (int i = 0; i < A.size(); i++)
    cout << A[i] << " ";
  cout << endl;

  // 5. Print the fragment pointed to by iterator it2
  cout << "it2 => ";
  while (it2 != A.end())
  {
    cout << *it2 << " ";
    it2++;
  }
}

Program result

A = 100 1 2 3 4 5
it2 => 100 1 2 3 4 5

 

7.4. Insert multiple items from a specified range

To insert a group of elements from another array that are specified by a range, use the following form of the insert() method

vector<T>::iterator insert<_Iter <unnamed>>(
    vector<T>::const_iterator _Where,
    _Iter _First,
    _Iter _Last
)

here

  • T – type of array elements;
  • _Where – an iterator that indicates the insertion position in the current array;
  • _First, _Last – iterators that point to the start and end positions of the source range of the array.

The method returns an iterator indicating the insertion position.

Example.

#include <iostream>
#include <vector>
using namespace std;

void main()
{
  // Method insert() - inserting a group of elements specified by a range

  // 1. Declare two arrays
  vector<short> A1(5);
  vector<short> A2(5);

  // 2. Fill arrays with data
  initializer_list<short> L1 = { 0, 1, 2, 3, 4 };
  initializer_list<short> L2 = { 5, 6, 7, 8, 9 };
  A1.assign(L1); // A1 = { 0, 1, 2, 3, 4 }
  A2.assign(L2); // A2 = { 5, 6, 7, 8, 9 }

  // 3. Implement insertion of elements with indices [1, 2, 3]   of array A2
  // into position 3 of array A1.
  // The resulting array must be like this: A1 = { 0, 1, 2, 6, 7, 8, 3, 4 }
  // 3.1. Declare an iterator to array A1 that points to position 3
  vector<short>::iterator Where = A1.begin() + 3;

  // 3.2. Declare iterators that point to the range [1..3] of array A2
  vector<short>::iterator First = A2.begin() + 1;
  vector<short>::iterator Last = A2.begin() + 4; // next after 3

  // 3.3. Call the method insert(), get the resulting iterator
  vector<short>::iterator Result;
  Result = A1.insert(Where, First, Last);

  // 4. Print the resulting array
  cout << "A1 = { ";
  for (int i = 0; i < A1.size(); i++)
    cout << A1[i] << " ";
  cout << "}" << endl;

  // 5. Print the fragment pointed to by the Result iterator
  cout << "Result => ";
  while (Result != A1.end())
  {
    cout << *Result << " ";
    Result++;
  }
}

Program result

A1 = { 0 1 2 6 7 8 3 4 }
Result => 6 7 8 3 4

 

8. Method assign(). Create array from existing data

The assign() method allows you to create a new array from an existing array or existing data. The assign() method has several overloaded implementations.

The first implementation allows you to modify an existing array and fill it with values

void assign(const size_t NewSize, const T& val)

here

  • T – type of array elements;
  • NewSize – new size of the array (number of elements);
  • val – the values with which the array is filled.

The second implementation allows you to form one array from another. The syntax for declaring such a form of the assign() method is as follows

void assign<_Iter, <unnamed>>(_Iter First, _Iter Last)

here

  • _Iter – iterator type;
  • First, Last – iterators pointing to the beginning and end of the range of the original array from which the new array is formed.

The third implementation allows you to form an array from an initialization list

void assign(initializer_list<T> _Ilist)

here

  • T – the type of the array elements;
  • _Ilist – initialization list.

Example.

...

// Method assign() - get a new array based on the data.
// 1. Declare an array of 0 elements of type int
vector<int> A;

// 2. Fill array A with 20 values
A.assign(3, 20); // A = [ 20, 20, 20 ]

// 3. Declare a new array of numbers and fill it with data
vector<int> A2(5);
A2[0] = 10;
A2[1] = 22;
A2[2] = 33;
A2[3] = 41;
A2[4] = 54;

// 4. Use iterators to create an array A based on A2.
// Take elements with positions 2 to 4 inclusive
vector<int>::iterator iStart;
vector<int>::iterator iEnd;
iStart = A2.begin() + 2; // set the iterator to the beginning of the array
iEnd = A2.begin() + 5; // set the iterator to the end of the array
A.assign(iStart, iEnd); // A = [ 33, 41, 54 ]

// 5. Create a new float array based on the initialization list
// 5.1. Declare initialization list
initializer_list<float> L = { 1.5f, 2.3f, -4.2f, 3.8f };

// 5.2. Declare an empty array of type float
vector<float> A3;

// 5.3. Initialize array A3 with list L
A3.assign(L);

cout << "------------" << endl;
for (int i = 0; i < A3.size(); i++)
  cout << A3[i] << " ";
cout << endl;

...

 


Related topics