C++

How do you swap Vectors in C++?

Let vtrA = {‘A’, ‘B’, ‘C’, ‘D’, ‘E’};
Let vtrB = {‘F’, ‘G’, ‘H’, ‘I’, ‘J’, ‘K’, ‘L’, ‘M’};

If vtrA becomes {‘F’, ‘G’, ‘H’, ‘I’, ‘J’, ‘K’, ‘L’, ‘M’} and

vtrB becomes {‘A’, ‘B’, ‘C’, ‘D’, ‘E’}

Then both vectors have been swapped. The fact that the vectors are of different lengths does not really pose a problem. For two vectors to be swapped, they must be of the same type.

The vector class has a member function to swap itself and another vector. The algorithm library has other swap functions with different names and for modified purposes. The main difference between the vector member swap() function and the algorithm swap functions is that, while the member function swaps its vector with another vector, the algorithm library swap functions, each swap two independent vectors.

The vector member function, swap(), will be discussed in this article, and the algorithm library swap functions will also be discussed. All vector code is done in the main() function for this article unless otherwise indicated.

Article Content

Vector Member swap() Function
void swap(vector&)

In the following program, two vectors are declared and their total contents are swapped:

#include <iostream>
#include <vector>
using namespace std;
   
int main()
{
    vector<char> vtrA = {'A', 'B', 'C', 'D', 'E'};
    vector<char> vtrB = {'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M'};
   
    vtrA.swap(vtrB);

    for (int i=0; i<vtrA.size(); i++) {
        cout << vtrA[i] << ' ';
    }
    cout << endl;

    for (int i=0; i<vtrB.size(); i++) {
        cout << vtrB[i] << ' ';
    }
    cout << endl;

    return 0;
}

The output is:

F G H I J K L M

A B C D E

The total contents of both vectors have been swapped. The vector library must be included to use a vector in C++, with the directive: #include .

In the program and in the main() function, the first segment declares the two vectors. The next code segment of one line that is,

vtrA.swap(vtrB);

swaps both vectors. It is clear that swap(vtrB) is a member function of the vector, vtrA. The two code segments coming after display the swapped contents.

Iterating with Iterators Instead of Indexes

A vector can be iterated with iterators instead of the Index. The following program shows how this can be done for the swapped vector contents:

#include <iostream>
#include <vector>
using namespace std;
   
int main()
{
    vector<char> vtrA = {'A', 'B', 'C', 'D', 'E'};
    vector<char> vtrB = {'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M'};
   
    vtrA.swap(vtrB);

    for (vector<char>::iterator p = vtrA.begin(); p != vtrA.end(); p++) {
        cout << *p << ' ';
    }
    cout << endl;

    for (vector<char>::iterator q = vtrB.begin(); q != vtrB.end(); q++) {
        cout << *q << ' ';
    }
    cout << endl;

    return 0;
}

The output is:

F G H I J K L M

A B C D E

Note the way the principal iterator is initialized in each for-loop. Note the while-condition in each for-loop. The principal iterator in each for-loop is incremented just like the index.

Swapping by Swapping Iterators

The algorithm library has a swap function called iter_swap(). This function swaps the two principal iterators of two independent vectors. The syntax is:

void iter_swap(ForwardIterator1 a, ForwardIterator2 b)

The following program shows how this algorithm-iter_swap() function, can be applied:

#include <iostream>>
#include <algorithm>
#include <vector>
using namespace std;
   
int main()
{
    vector<char> vtrA = {'A', 'B', 'C', 'D', 'E'};
    vector<char> vtrB = {'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M'};

    vector<char>::iterator u = vtrA.begin();
    vector<char>::iterator v = vtrB.begin();
    swap(u, v);

    for (u = u; u != vtrB.end(); u++) {
        cout << *u << ' ';
    }
    cout << endl;

    for (v = v; v != vtrA.end(); v++) {
        cout << *v << ' ';
    }
    cout << endl;

    return 0;
}

The output is:

F G H I J K L M

A B C D E

Note that the algorithm library had to be included. The featured code segment for this program is:

vector<char>::iterator u = vtrA.begin();

vector<char>::iterator v = vtrB.begin();

swap(u, v);

For the first of these statements, u points to ‘A’ of the vector, vtrA. For the second statement, v points to ‘F’ of the vector, vtrB. The third statement swaps the pointing. With it, u now points to ‘F’ of vtrB and v points to ‘A’ of vtrA. u can now be used to iterate through the elements of vtrB, and v can now be used to iterate through the elements of vtrA.

Range

For the vector,

{'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M'}

the sequence,

'H', 'I', 'J', 'K'

is a range.

The iterations for this range, can be gotten as follows:

vector<char> vtr = {'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M'};
vector<char>::iterator itB = vtr.begin();
itB++; itB++;
vector<char>::iterator itE = vtr.end();
itE--; itE--; itE--;

cout << *itB << ' ' << *itE << endl;

The output is:

H K

The expression, vtr.begin(), returns an iterator that points to ‘F’. The expression, vtr.end(), returns an iterator that points just after the last element of the vector. The iterator has to be incremented twice to make the iterator that points to ‘F’ to point to ‘H’. To make the iterator that points, just beyond the vector, to point to ‘K’, that iterator has to be decremented three times and not two times. When it is decremented the first time, it points to the last element, ‘M’. When decremented the second time, it points to the element before, ‘L’. And when decremented the third time, it points to the element, ‘K’. *itB returns the value of the element itB was last pointing to. *itE returns the value of the element itE was last pointing to.

So the range, by iterators, is:

[itB, itE)

‘)’ at the end of the range notation means that, if the range is to be fitted into another vector or swapped with another vector, the last value of the range, represented by itE, will not be involved. That is, only elements from itB to the one just before, itE will be copied or swapped.

Swapping Range with the whole Vector

The algorithm library has a function to swap a range in one vector with another whole vector. The syntax for the function is:

ForwardIterator2 swap_ranges(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2)

first1 represents the iterator that points to the first element of the range. last1 represents the iterator that points to the last element of the range. This last element is just a delimiter; it will not be involved in the swapping. first2 points to the first element of the inserting vector. The function returns an iterator that points to the next element, not swapping the whole vector – see following code. The following program illustrates this swapping with the swap_ranges() function.

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
   
int main()
{
    vector<char> vtrB = {'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M'};
    vector<char>::iterator itB = vtrB.begin();
    itB++; itB++;
    vector<char>::iterator itE = vtrB.end();
    itE--; itE--; itE--;

    vector<char> vtrA = {'A', 'B', 'C', 'D', 'E'};

    vector<char>::iterator itR = swap_ranges(itB, itE, vtrA.begin());

    for (int i=0; i<vtrB.size(); i++)
        cout << vtrB[i] << ' ';
    cout << endl;

    cout << *itR << endl;

    for (int i=0; i<vtrA.size(); i++)
        cout << vtrA[i] << ' ';
    cout << endl;

    return 0;
}

The output is:

F G A B C K L M

D

H I J D E

Notice that the whole vector has not been swapped. Instead, it is just the first three values of the whole vector that has been swapped, with the third, fourth, and fifth values of vtrB. The sixth element of vtrB was not involved, and that was expected.

VtrA has 5 elements, while vtrB has 8 elements. In order to truly swapped the whole vector, vtrA of 5 elements, the sequence in vtrB concerned, needs to have 6 elements (with the sixth element being just a delimiter). The following program illustrates this:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
   
int main()
{
    vector<char> vtrB = {'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M'};
    vector<char>::iterator itB = vtrB.begin();
    itB++; itB++;
    vector<char>::iterator itE = vtrB.end();
    itE--;

    vector<char> vtrA = {'A', 'B', 'C', 'D', 'E'};

    vector<char>::iterator itR = swap_ranges(itB, itE, vtrA.begin());

    for (int i=0; i<vtrB.size(); i++)
        cout << vtrB[i] << ' ';
    cout << endl;

    cout << *itR << endl;

    for (int i=0; i<vtrA.size(); i++)
        cout << vtrA[i] << ' ';
    cout << endl;

    return 0;
}

The output is:

F G A B C D E M

H I J K L

This time, all 5 values of vtrA were swapped with the third, fourth, fifth, sixth, and seventh values of the vtrB. So, to truly swapped a whole vector, the longer vector should have the corresponding number of elements (in sequence).

Conclusion

Swapping two vectors means exchanging the contents of one vector with that of another. For vectors to be swapped, they have to be of the same type. C++ has a member function to do this. This means that one vector’s swap() member function takes the other vector as an argument, then exchanges the contents. If the programmer wants more swapping features, such as swapping the iterators or swapping a range in one vector with the total list of another vector, he has to use the algorithm library.

About the author

Chrysanthus Forcha

Discoverer of mathematics Integration from First Principles and related series. Master’s Degree in Technical Education, specializing in Electronics and Computer Software. BSc Electronics. I also have knowledge and experience at the Master’s level in Computing and Telecommunications. Out of 20,000 writers, I was the 37th best writer at devarticles.com. I have been working in these fields for more than 10 years.