Vectors in C++ - intro and some properties - UCS - Unleash-Coding-Skills

Saturday, 24 March 2018

Vectors in C++ - intro and some properties - UCS

Vectors in C++:

C++ has a vector class within the std namespace. A vector is similar to an array, in a sense where a series of elements are stored with the same variable name. Unlike arrays, vectors are dynamically sized, which is a major advantage.You can also apply sort and you can also use generic data types or structures as array element instead of primitive data types.

You should have to include the header

#include<vector> in your program in cpp.

Syantax:

Vector < datatype> x;

you can also give size to your vector

Vector <datatype> x(sizeof your vector or array)
eg: vector <int> x(20);
      vector<string>v(20);

Inserting in to your vector:

Suppose 'x' is name of your vector as you declared earlier.Then inserting a element in to a vector be like.

x.push_back(value); 

//if size of  vector is declared earlier you can also insert into it like normal array

x[index]=value;

 Accessing the vector in our programs:

x[index];
eg:int l=x[index];

Size of your dynamic vector:

x.size();

All above things are explained with example in this program.

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int>v;
    v.push_back(10);
    v.push_back(7);
    v.push_back(20);
    int sum=0;
for(int i=0;i<v.size();i++)
{
      cout<<v[i]<<" ";
      sum+=v[i];
}
cout<<endl;
cout<<"sum of vector elements is "<<sum;
    return 0;
}

output:
10 7 20
sum of vector elements is 37

More about Vectors go to this link:

Vectors in CPP part-2

Happy coding
Feel free to comment..........

No comments:

Post a comment