C++

Looping Through a Vector in C++

To loop through a vector means to access all the elements of the vector from the beginning to the end, or from the end to the beginning. The elements may be accessed for reading or writing (changing value) or both.

In C++, the vector can be looped through using the classic for-loop with the subscript (index) in the square brackets. It can be looped through using the range-based for-statement. It can be looped through using the for_each() function included from the algorithm library.

Article Content

– Looping using the classic for-loop

– Looping using the range-based for-statement

– Looping using the for_each() Function

– Conclusion

Looping Using the Classic For-Loop

Subscript

Consider the following code segment:

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

char ch = vtr[2];

cout << ch << endl;

The output is ‘C’. In the second statement, after the vector name, vtr, is the square brackets. Inside the square brackets is the index, which is also the vector subscript. Index counting begins from zero. The index in the code is 2, which returns the third element of the vector.

Looping with Subscript

To loop with subscript or iterator, the for-loop has to be used. The while-loop or do-while loop can also be used, but the for-loop is most convenient. The syntax of a for-loop is:

for (beginning_state; while_condition; next/previous) {

//statements

}

Looping Forward

The following program uses a for-loop to loop forward, a vector of characters (chars), by subscript:

#include <iostream>

#include <vector>

using namespace std;

int main()

{

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

for (int i=0; i<vtr.size(); i++) {

char ch = vtr[i];

cout << ch << ' ';

}

cout << endl;

return 0;

}

The output is:

A B C D E

The vector library has to be included in order for vector class to be used. In the C++ main function, after the creation of the vector is the for-loop. This for-loop can be summarized as follows: Read each element of the vector beginning from index, 0; and while the end of vector is not yet reached, increase the index by 1 in order to read the next element.

The parentheses of the for-loop have the logic of what to read next, while the block of the for-loop does the reading and printing at the terminal (console).

Looping Forward and Skipping

In the above loop, the next statement in the parentheses is i++. This is the same as:

i = i + 1

With this, the elements are read one after the other in the forward direction. In order to read every other element (skipping one element each time), the next argument in the parentheses, has to be

i = i + 2; which is the same as i+=2;

The following code reads out every other character:

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

for (int i=0; i<vtr.size(); i+=2) {

char ch = vtr[i];

cout << ch << ' ';

}

cout << endl;

The output is:

A C E

skipping ‘B’ and ‘D’.

Looping Backwards

The following code uses a for-loop to loop backwards, a vector of characters (chars):

int main()

{

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

for (int i=vtr.size()-1; i<vtr.size(); i--) {

char ch = vtr[i];

cout << ch << ' ';

}

cout << endl;

return 0;

}

The output is:

E D C B A

The looping begins from the highest index (4), which is given by:

vtr.size()-1

In this case, the vector member function, size() returns 5. 1 has to be subtracted from it to obtain the highest index of 4 (index counting begins from 0). To loop backwards, the previous statement in the parentheses, is now “i–”.

Looping Backward and Skipping

In the above loop, the previous statement is i–. This is the same as:

i = i - 1

With this, the elements are read one after the other in the reverse direction. In order to read every other element (skipping one element each time) backwards, the previous statement has to be

i = i - 2; which is the same as i-=2;

The following code reads out every other character, backwards:

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

for (int i=vtr.size()-1; i<vtr.size(); i-=2) {

char ch = vtr[i];

cout << ch << ' ';

}

cout << endl;

The output is:

E C A

skipping ‘D’ and ‘B’.

Looping Using an Iterator Class

A vector can be looped with an iterator. There are six vector iterator classes. Only two are used here. The names of the two are: iterator and reverse_iterator. In the illustrations here, the for-loop is still used as the loop.

An iterator is an elaborated pointer. For each iterator, there is a class from which objects can be instantiated. The instantiated object is the iterator.

Looping Forward

The following program uses a for-loop to loop forward, a vector of characters (chars), by iterator:

#include <iostream>

#include <vector>

using namespace std;

int main()

{

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

vector<char>:: iterator iter = vtr.begin();

for (iter = iter; iter<vtr.end(); iter++) {

char ch = *iter;

cout << ch << ' ';

}

cout << endl;

return 0;

}

The output is:

A B C D E

Observe how the iterator object, iter has been declared. The vector has the member function begin(). This returns an iterator that points to the first element of the vector. There is another member function, end() for the vector. This returns an iterator that points just after the last element of the vector. The iterator returned by end() is very compatible to the iterator returned by begin(). In fact, they are of the same type, iterator.

In the parentheses, the beginning-state is:

iter = iter;

The means that the left operand, iter, should begin the scanning from where the right operand, iter is pointing to.

This for-loop with iterators can be summarized as follows: Read each element of the vector beginning from that pointed to by iter; and while the end of vector is not yet reached, increment the iterator, iter, to point to the next element in order to read the next element.

The body of the for-loop is:

char ch = *iter;

cout << ch << ' ';

The asterisk in this position, is an indirection operator. It obtains the value pointed to, by the iterator

Looping Forward and Skipping with Iterator

In the above loop, the next argument is, iter++. This is the same as:

iter = iter + 1

Plus-one with the iterator, means point to the next element. It does not mean, add the integer 1, to the iterator. With this, the elements are read one after the other in the forward direction. In order to read every other element (skipping one element each time), the next argument has to be

iter = iter + 2; which is the same as iter+=2;

The following code reads out every other character:

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

vector<char>:: iterator iter = vtr.begin();

for (iter = iter; iter<vtr.end(); iter+=2) {

char ch = *iter;

cout << ch << ' ';

}

cout << endl;

The output is:

A C E

skipping ‘B’ and ‘D’.

Looping Backwards

The following code uses a for-loop to loop backwards, a vector of characters (chars), using iterators:

int main()

{

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

vector<char>::reverse_iterator iter = vtr.rbegin();

for (iter = iter; iter<vtr.rend(); iter++) {

char ch = *iter;

cout << ch << ' ';

}

cout << endl;

return 0;

}

The output is:

E D C B A

The reverse_iterator has been used here. The vector has a corresponding member function, rbegin(), that returns an iterator that points to the last element of the vector. There is another member function, rend(), that returns an iterator that points just before the first element of the vector.

To loop backwards, the previous statement in the parentheses, is still ironically, “iter++”. And the while-condition, still ironically has ‘<’.

Looping Backwards and Skipping

In the above loop, the previous statement is, iter++. This is the same as

iter = iter + 1

With this, the elements are read one after the other in the reverse direction. In order to read every order element (skipping one element each time) backwards, the previous statement has to be

iter = iter + 2; which is the same as iter+=2;

The following code reads out every other character backwards:

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

vector<char>::reverse_iterator iter = vtr.rbegin();

for (iter = iter; iter<vtr.rend(); iter+=2) {

char ch = *iter;

cout << ch << ' ';

}

cout << endl;

The output is:

E C A

skipping ‘D’ and ‘B’.

Looping Using the Range-Based For-Statement

The range-based for-statement is a more convenient statement to use to loop through a list, such as a vector. It is not really used for skipping or looping backwards. The syntax is:

for ( init-statement-optional for-range-declaration : for-range-initializer ) statement

This time, there are two statements in the parentheses and not three. The first statement is the declaration of a variable that holds the next element in the vector. This variable has to be of the same type as the type of vector elements. The second argument after the colon is the name of the vector.

The following code shows how it can be used:

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

for (char ch : vtr) {

cout << ch << ' ';

}

cout << endl;

The output is:

A B C D E

Looping Using the for_each() Function

The for_each() function is used from the included algorithm library. The syntax is:

template<class InputIterator, class Function>

constexpr Function for_each(InputIterator first, InputIterator last, Function f);

The first argument is an iterator that points to the first element of the vector. The second argument is an iterator that points just after the last element of the vector. The third argument is the name of a function, whose body is what would be in the classic for-loop. This function has one parameter, and it is the declaration of the variable that would hold the next value of the vector. It has to be of the same type as each element in the vector. This for_each() function is not really used for skipping or looping backwards.

The following program shows how to use the for_each() function call, and an associated function definition:

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

void func (char ch) {

cout << ch << ' ';

}

int main()

{

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

for_each(vtr.begin(), vtr.end(), func);

cout << endl;

return 0;

}

The output is:

A B C D E

Conclusion

To loop through a vector, means to access all the elements of the vector, from the beginning to the end, or from the end to the beginning. The elements may be accessed for reading or writing (changing value) or both.

In C++, the vector can be looped through, using the classic for-loop, with the subscript (index) in the square brackets; it can be looped through using the range-based for-statement; it can also be looped through using the for_each() function included from 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.