C++

How Do You Expand a Vector in C++?

If “expand” here means include more elements in the vector so that its size (length) increases, then a vector can be expanded. However, “expanding a vector” is not a classical phrase in C++. In fact, “expand” in C++ actually means, replace the name of an object with the values of its content.If a vector consists of string literals, then the vector can be replaced by one string made up of the string literals. However, this has to be done manually. That is, it has to be done by the programmer and not by a library.

Notwithstanding, this post will explain how to replace a vector of string literals, with one string of the literals. This post will also explain the different ways in which the C++ vector can be increased in length. The length of a vector in C++ is called the size.

The vector has member functions. Its size can be increased using the member functions: resize(), insert(), emplace() and push_back(). This article explains the different ways in which the vector can be expanded, that is, increased in size; and in the case of vector of string literals, replaced by all the string literals.

Do vector coding inside the main() function body, unless there is a good reason to do it before the main() function body. Do not forget to begin the program with:

#include <iostream>

#include <vector>

using namespace std;

Article Content

Vector of Strings to One String

A vector of string literals can be replaced by one string of the literals. The literals will be separated by commas in the one string. The following code illustrates this:

vectorvtr = {"Toyota", "Mitsubishi", "Ford", "Mercedes", "Jeep"};

    char arrChars[100];
    int ctr = 0;    //counter
    int i=0;
    for (i=0; i<vtr.size(); i++) {
        const char* str = vtr[i];
        int j=0;
        for (j=0; str[j] != '\0'; j++) {
arrChars[ctr] = str[j];
            ++ctr;
        }
arrChars[ctr] = ',';  ++ctr; arrChars[ctr] = ' ';
        ++ctr;
    }

arrChars[ctr] = '\0';

cout<<arrChars<<endl;

The output is:

Toyota, Mitsubishi, Ford, Mercedes, Jeep,

which is one long string. An array string and a string literal in double quotes, are fundamentally the same thing, ending in ‘\0’; though the ending for the double quote string literal is implicit. The final one long string has only one ‘\0’ at the end of the character sequence. The code can still be modified to remove the last comma and space.

Increasing Vector Size

Resizing

The size() member function can be used to return the size() of a vector as the following code shows:

vectorvtr{'F', 'G', 'H', 'I', 'J'};
cout<<vtr.size() <<endl;

The output is 5.

void resize(size_type sz)

To increase the size of a vector, the vector should be resized to a bigger number. The following code does this using the member function, resize(size_type sz):

    vectorvtr{'F', 'G', 'H', 'I', 'J'};
vtr.resize(7);
vtr[5] = 'K';
vtr[6] = 'L';

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

The output is:

F G H I J K L

When a vector is just resized with the resize() member function, new empty locations are made available towards the end of the vector. These new locations can then be filled.

void resize(size_type sz, const T& c)

The same value can be added to the new locations towards the end of the vector using this resize() overloaded method. Illustration:

vectorvtr{'F', 'G', 'H', 'I', 'J'};
vtr.resize(8, 'Z');

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

The output is:

F G H I J Z Z Z

Inserting

Inserting takes place in front of the element pointed to by the iterator.

insert(const_iterator position, const T& x)

The following code shows how this function is used:

vectorvtr{'F', 'G', 'H', 'I', 'J'};
    vector::iterator p = vtr.begin();
    p++, p++;

    char id = 'Z';
vtr.insert(p, id);

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

The output is:

F G Z H I J

‘Z’ has been inserted in front of H. The begin() member function returns an iterator that points to the first element of the vector. The iterator can then be incremented to the desired position. Note that the expected second argument for insert() here, is an identifier.

iterator insert(const_iterator position, T&& x)

The following code shows how this function is used:

vectorvtr{'F', 'G', 'H', 'I', 'J'};
    vector::iterator p = vtr.begin();
    p++, p++;

vtr.insert(p, 'Z');

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

The output is:

F G Z H I J

‘Z’ has been inserted in front of H. The begin() member function returns an iterator that points to the first element of the vector. Note that the expected second argument for insert() here, is a literal.

iterator insert(const_iterator position, size_type n, const T& x)

The same value can be inserted more than once. The following code illustrates this:

vectorvtr{'F', 'G', 'H', 'I', 'J'};
    vector::iterator p = vtr.begin();
    p++, p++;

    char id = 'Z';
vtr.insert(p, 3, id);

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

The output is:

F G Z Z Z H I J

iterator insert(const_iterator position, InputIterator first, InputIterator last)

A range from another vector can be inserted. The following code illustrates this:

vector otherVtr = {'K', 'L', 'M', 'N', 'O'};
    vector::iterator i = otherVtr.begin();
i = i + 1;
    vector::iterator j = otherVtr.end();
    j = j - 2;

    vectorvtr{'F', 'G', 'H', 'I', 'J'};
    vector::iterator p = vtr.begin();
    p++, p++;

vtr.insert(p, i, j);

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

The output is:

F G L M H I J

For the other vector, the range is obtained as follows: The begin() member function returns an iterator that points to its first element. This iterator, i was incremented to point to the next element. The end() member function returns an iterator that points just after the last element. This iterator, j was decremented twice by subtracting 2 from it, and it then pointed to the element, ‘N’.

At this point, the range imagined is:

'L', 'M', 'N'

However, with C++, the last element in a range will not be involved (inserted). So, only “'L', 'M'” is inserted.

iterator insert(const_iterator position, initializer_list<T> il)

A vector literal list can be inserted. The following code illustrates this:

vectorvtr{'F', 'G', 'H', 'I', 'J'};
    vector::iterator p = vtr.begin();
    p++, p++;

vtr.insert(p, {'K', 'L', 'M', 'N', 'O'});

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

The output is:

F G K L M N O H I J

Emplace

The use of emplace() is similar to the use of insert(), and many programmers prefer it to insert().

Emplace within

For the following code, ‘Z’ is emplaced within the values, ‘F’, ‘G’, ‘H’, ‘I’, ‘J’:

vectorvtr{'F', 'G', 'H', 'I', 'J'};
    vector::iterator p = vtr.begin();
    p++, p++;

vtr.emplace(p, 'Z');

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

The output is:

 

Emplace in front

For the following code, ‘Z’ is emplaced in front of the values, ‘F’, ‘G’, ‘H’, ‘I’, ‘J’:

vectorvtr{'F', 'G', 'H', 'I', 'J'};
    vector::iterator p = vtr.begin();

vtr.emplace(p, 'Z');

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

The iterator returned by begin() was not incremented; and so the output is:

Z F G H I J

Push_Back

The push_back() member function can be used to append an element. The following code illustrates this:

vectorvtr{'F', 'G', 'H', 'I', 'J'};

vtr.push_back('Z');

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

The output is:

F G H I J Z

An element can also be appended using the emplace_back() member function. The following code illustrates this:

vectorvtr{'F', 'G', 'H', 'I', 'J'};

vtr.emplace_back('Z');

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

The output is:

F G H I J Z

Knowing the Length of a Vector

The size of a vector means the number of elements in the vector. This can be obtained using the size() member function. The following program illustrates this:

#include
    #include
    using namespace std;

    int main()
    {

        vectorvtr = {'F', 'G', 'H', 'I', 'J', 'K'};

        int sz = vtr.size();

cout<<sz<<endl;

        return 0;
    }

The output is 6.

Capacity of a Vector

The capacity of a vector should not be confused with the size of the vector. When a vector is being manipulated and increased, the locations of its elements in the computer’s memory are being changed (reallocated). The capacity of a vector is the total number of elements the vector can hold without requiring reallocation. It defers with the initial size of the vector. The following program illustrates this for an empty vector, and for a vector of 5 elements:

#include
    #include
    using namespace std;

    int main()
    {
        vector vtr1;
        vector vtr2{'F', 'G', 'H', 'I', 'J'};

        int cap1 = vtr1.capacity();
        int cap2 = vtr2.capacity();

cout<< cap1 <<endl;
cout<< cap2 <<endl;

        return 0;
    }

The output is:

0

5

Reserving Space for Vector

void reserve(size_type n)

Vector space can be reserved with this function. The following program reserves a space of 5 elements:

#include
    #include
    using namespace std;
    int main()
    {
        vectorvtr = {'F', 'G', 'H'};

vtr.reserve(5);
        int cap = vtr.capacity();

cout<< "New Capacity: " << cap <<endl;

vtr.push_back('I');
vtr.push_back('J');
vtr.push_back('K');

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

        return 0;
    }

The output is:

New Capacity: 5

F G H I J K

The reserved spaces include those for the initial elements. The fact that 5 spaces were reserved, does not mean that an element cannot be appended beyond 5 elements.

Conclusion

“Expanding a vector” is not a classical phrase in C++. However, if “expanding a vector” means, increasing the length of a vector, then, yes, a vector can be expanded. In C++ the length of a vector or any C++ container, is called the size. The vector can be expanded with the following member functions: resize(), insert(), emplace() and push_back(). Other related member functions are: size(), capacity(), and reserve(). In many C++ programs, a vector would be increased and decreased a number of times. A vector can be decreased, using the erase member function – see later. If a vector consists of string literals, then the vector can be replaced by one long string made up of the string literals.

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.