Vectors in C++

Vectors in C++ is an interesting data structure which is bit similar to arrays. Not having a fixed size is the main difference though. The vector class is in C++ std namespace.

Vectors are associated with some useful methods which are handy in controlling vectors. Refer to the guide for more info.

Method push_back( ) to be used to add elements to a vector. Accessing an element can be done through accessing the relevant index as in arrays. size( ) gives the number of elements in a vector.

Defining a Vector

Creating an instance of the vector class.


#include <iostream>
#include <vector>

using namespace std;

int main()
{
   vector<string> names;
   
   cout << "Size of the vector : " << names.size() << endl;
   return 0;
}

Assign Values to a Vector


#include <iostream>
#include <vector>

using namespace std;

int main()
{
   vector<string> names;
   names.push_back("Alex");
   names.push_back("Bob");
   
   cout << "Size of the vector :" << names.size() << endl;
   cout << "First Name :" << names[0] << endl;
   
   names[0] = "Alex the great";
   
   cout << "First Name :" << names[0] << endl;
   
   return 0;
}

Example

Here is an example on how vectors can be used to solve a problem.

Write a function that accepts an upper bound positive integer and then calculate all the prime numbers within the given integer (excluding). Prime number set should starts with 2 in the index = 0.


#include <iostream>
#include <vector>

using namespace std;

vector<int> get_primes(int num);
bool is_prime(int num);

int main()
{
   vector<int> output;
   output = get_primes(20);
   
   for(int j=0; j < output.size(); j++){
       cout << "Prime No at index - " << j << " = " << output[j] << endl;
   }
   
   return 0;
}

vector<int> get_primes(int limit){
    vector<int> primes;
    for(int i = 2; i < limit; i++){
        if(is_prime(i)){
            primes.push_back(i);
        }
    }
    return primes;
}

bool is_prime(int num){
    for(int i = 2; i<num; i++){
        int r = num % i;
        if(r ==0){
            return false;
        }
    }
    return true;
}

Output

Prime No at index - 0 = 2
Prime No at index - 1 = 3
Prime No at index - 2 = 5
Prime No at index - 3 = 7
Prime No at index - 4 = 11
Prime No at index - 5 = 13
Prime No at index - 6 = 17
Prime No at index - 7 = 19

The code is self-explanatory. Notice how vectors are used in methods. Assigning values and accessing the indexes.

Advertisements

Please add your valuable idea below, will make a discussion, thanks !

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s