Jul 18
Friday
C++
Simple Data Structure - The Vector

The vector is a simple data structure that allows you to store values with the same data type in one container.

Introduction

Without the use of a data structure, how would you store multiple variables? Let’s say we wanted to store 5 names into strings. How would this be done?

string name1,name2,name3,name4,name5;
cin >> name1 >> name2 >> name3 >> name4 >> name5;

That looks a bit ugly doesn’t it? What if we wanted to store the number of names the user wanted to input? That is where the vector comes in.

The Vector

#include <vector> //You need to include this library to use the vector

//Syntax:
vector <data_type> name;

To populate our vector with 5 names, we would simply do the following:

vector <string> names;

string input;
for ( int i = 0; i < 5; i++ ) {
     cin >> name;
     names.push_back(input);
}

In other words, we simply ask the user five times with our for loop, to type in the terminal a name, and it will be push_back‘ed onto our vector. Every single time we use the push_back member function of the vector, we simply push the newly inserted element to the back. Let’s use the following visual example of a vector.


Notice how the positions are labeled. The size of the vector is the number of elements in the vector. To create this vector, we would do the following.

vector <string> names;
names.push_back("Joe");
names.push_back("Beth");
names.push_back("Mary");
names.push_back("Jon");
names.push_back("Sue");

How would we access and print out a variable?

Printing out elements of the vector

To print out an element we would simply do the following:

cout << names[0];

This allows us to print out the value that is contained in position zero. Therefore, “Joe”.


To find out the size of our vector we would simply do:

cout << names.size();

This would print out 5 since our vector contains 5 elements.


To remove an element from our vector we would simply do:

names.pop_back();

This would remove “Sue” from our vector, giving it a size of 4.

Doing more with the vector

Challenge 1: Populate a vector with 5 integer values, and print them all out.
Challenge 2: Print out all the elements of a vector using a for loop.

What now?

Join our forums and discuss your newly discovered vector! Remember, there is still so much more to learn with how to use a vector, this is simply a tutorial for beginners and isn’t meant for advanced users.

Not yet Rated!1 Star2 Stars3 Stars4 Stars5 Stars



Post a Comment