Vector in C++: STL Containers

Share the Article

What is a Vector in C++

Vector in C++ is a type of STL container which is used for storing elements in sequential manner just like arrays. One major difference between Vectors and arrays is that in case of array the size is fixed. Changing size of an array dynamically is not at all feasible. However with Vectors, we are having advantage of changing size dynamically based on need.

For Example

int a[5]; // Array a with fixed size 5 int b[100]; // Array b with fixed size 100 char c[300]; // Array c with fixedsize 300

As seen above, we have created array a, b and c of size 5,100 and 300. There is no provision to change the size later on. Therefore, if we try to access location a[20] or b[300] it shall generate runtime crash .

However, with vector we do not have such limitations. We can say vector is a more dynamic form of arrays where it is having all its feature of insertion, deletion plus change of size also.

When to implement Vector

Below are the ideal cases for implementing or using a Vector inside an application:

  • Not aware how many elements we can store at runtime
  • Need sequential access of elements in fixed time
  • Mainly a new element should get inserted at the end position

In conclusion, if above all statements above are true, then we have ideal case to implement Vector in your application.

Which Header File for Vector

We need to include below header file in our application if we want to implement Vector in our application.

#include<vector>

How to create Vectors

Like array we can create Vector for any data type, including user-defined data types also.

For example

vector<int> i; // vector i for integer data vector<char> c; // vector c for character data vector<float> f; // vector f for float data vector<a> ud; // vector ud for user-defined data type "a"

How to Initialize a Vector

Like array, we can also initialize Vector.

For example:

vector<int> i ={1,2,3,4,5}; // vector i initialized vector<char> c ={'a','b'}; // vector c init. with a and b

How to print size of a Vector

In below section, details about Vector operators for inserting and printing elements are captured.

size( ) : Printing Current Size of vector

In order to print current size of Vector we are having size( ) method.

Below example is depicting how to get the current size of Vectors.

#include <iostream> #include <vector> using namespace std; int main () { vector<int> v; // vector v for storing int cout << "size: " << v.size() << endl; // printing size of vector return 0; }

Output

vector size method in c++

As seen above, we have created Vector v for storing integer elements. At anytime, we can print the size of vector using size( ). For above example, we have not added any element therefore we shall get size as 0.

How to print Vector elements

iterator: for iterating element of vector.

For iterating or accessing element in array we need index location and with that we can access its element.

For example

int a[5]; //Array of integer for(int i=0; i<5; i++) cout<< a[i] << endl;

Similarly, in Vector for accessing its element we have iterator. Iterator support us for accessing all elements of a Vector.

For example, below application depicting how to implement iterator for Vector:

#include <iostream> //main header for io #include <vector> //for vectors using namespace std; //for namespace int main () { vector<int> v ={1,2,3,4,5}; vector<int>::iterator it; cout<<"Printing vector elements"<<endl; for(it=v.begin();it!= v.end(); ++it) { cout<< *it << endl; } return 0; }

vector: begin( ) and end( ) for returning front and end elements

array[0] return the first element and array[n-1] return the last element of the array. Similarly we can get first and last element for Vector with begin( ) and end( ) members.

vector<int> v; v.begin() // return iterator at front position v.end() // return iterator at last position

How to insert a new element in Vectors

push_back( ): Inserting element at last

Since vector is a sequential container, therefore, at any time we can insert element at its end position by using push_back( ).

For example, in order to add 3 elements in vector we need to call push_back( ) 3 times. Below is the example for adding 3 elements at the end of a Vector.

#include <iostream> #include <vector> using namespace std; int main () { vector<int> v; cout << "Initial size: " << v.size() << endl; v.push_back(10); v.push_back(20); v.push_back(30); vector<int>::iterator it; cout << "After pushing 3 elements size: " << v.size() << endl; for(it = v.begin(); it != v.end(); ++it) { cout<<*it<<endl; } cout << "Final size: " << v.size() << endl; return 0; }

In above example, after calling push_back( ) 3 times, the size of vector got changed to 3 from 0.

example for push_back method

In conclusion, we are dynamically changing the size of vector by adding element at runtime.

insert( ): Inserting an element at any specific position

In order to add element at any position in Vector, we are having insert( ) member.

For example, below is the sample application for inserting an element at any location:

#include <iostream> //main header for io #include <vector> //for vectors using namespace std; //for namespace int main () { vector<int> v ={1,2,3}; cout << "Initial size: " << v.size() << endl; v.insert(v.begin(), 40); cout << "After Inserting at beginning: " << v.size() << endl; v.insert(v.begin()+4,50); cout << "After inserting at 4th position: " << v.size() << endl; vector<int>::iterator it; cout << "The vector contents:" << endl; for(it = v.begin(); it != v.end(); ++it) { cout<<*it<<endl; } return 0; }

As seen in above application, we have inserted data at the beginning and at 4th position of Vector v.

emplace( ): For inserting data

We can also insert data at any position by using emplace( ) operator . It will increase the size of vector by 1.

The detailed analysis between push & emplace is present in C++ vector : emplace_back Vs push_back

Below is the example for the same:

#include <iostream> //main header for io #include <vector> //for vectors using namespace std; //for namespace int main () { std::vector<int> v = {1,2,3}; cout<<"vector size "<<v.size()<<endl; v.emplace ( v.begin(), 5 ); v.emplace ( v.end(), 8 ); cout<<"After emplace vector size "<<v.size()<<endl; return 0; }

Output

emplace method in vector in c++

How to delete element from Vector

In array, there is no option to shrink the size of array or remove an element. However, in Vector we have support for erasing an element or clearing all its elements.

erase( ) : erasing or deleting element from vector

For example, below sample application is erasing 2nd element from vector.

#include <iostream> //main header for io #include <vector> //for vectors using namespace std; //for namespace int main () { vector<int> v ={1,2,3,4,5}; cout << "Initial size: " << v.size() << endl; vector<int>::iterator it; cout<<"Printing vector elements"<<endl; for(it=v.begin();it!=v.end(); ++it) { cout<<*it<<endl; } v.erase (v.begin()+2); // remove the 3rd element cout<<"Printing vector elements after erasing"<<endl; for(it=v.begin();it< v.end(); ++it) { cout<<*it<<endl; } cout << "After erasing 2nd elements size: " << v.size() << endl; return 0; }

Output

erase method in vector in c++

clear( ): Clearing or removing all elements

Below example demonstrating how to erase or clear all elements from vector:

#include <iostream> //main header for io #include <vector> //for vectors using namespace std; //for namespace int main () { vector<int> v ={1,2,3,4,5}; cout << "Initial size: " << v.size() << endl; vector<int>::iterator it; cout<<"Printing vector elements"<<endl; for(it=v.begin();it!=v.end(); ++it) { cout<<*it<<endl; } v.clear (); // clear all element cout<<"Printing vector elements after erasing"<<endl; for(it=v.begin();it< v.end(); ++it) { cout<<*it<<endl; } cout << "After erasing 2nd elements size: " << v.size() << endl; return 0; }

Output

example for clear member

How to allocate Vector in C++

As seen above, size( ) returns the number of elements the vector is holding at that time. But we also have members for dealing with allocation.

capacity( ): Storage allocations

It returns the maximum storage allocated for vector at that moment. However, such allocation can be larger or equal to size of the Vector. Ideally, capacity depicts how many elements vector can accommodate without doing reallocation.

For example: Below applciation is printing current capacity and size of the Vector.

#include <iostream> //main header for io #include <vector> //for vectors using namespace std; //for namespace int main () { vector<int> v; cout << "Initial size: " << v.size() << endl; cout << "Initial capacity: " << v.capacity() << endl; for(int i =0;i<1000;i++) v.push_back(30); cout << "After pushing elements size: " << v.size() << endl; cout << "After pushing elements capacity: " << v.capacity() << endl; return 0; }

Output

example demonstrating vector capacity

max_size( ): print maximum allocation possible

In order to print maximum element which Vector can accommodate, we have max_size( ). It depicts the maximum size which container can take. There is also no guaranty that container will reach such size, it again depends on system library implementation.

Below ex:

#include <iostream> //main header for io #include <vector> //for vectors using namespace std; //for namespace int main () { vector<int> v; cout << "Initial size: " << v.size() << endl; cout << "Initial capacity: " << v.capacity() << endl; cout<< "Maximum allocation : "<<v.max_size()<<endl; for(int i =0;i<1000;i++) v.push_back(30); cout << "After pushing elements size: " << v.size() << endl; cout << "After pushing elements capacity: " << v.capacity() << endl; cout << "After pushing elements capacity: " << v.max_size() << endl; return 0; }

Output

example demonstrating vector::max_size

How Vector in C++ do Memory management

As we know, Vector supports dynamic memory allocation. So, it is possible to keep inserting element in vector. But it may happen that next memory allocation is not possible and in this case, vector needs to reallocate all elements and move them to new larger allocation. Such process seems to be an overhead for system performance. Therefore, in order to save such reallocation, the vector always allocates more memory than is required. Therefore, Vectors are having 2 operations, first is size( ) which gives current memory required for storing all elements. And second is the capacity( ), which gives how much elements vector can insert without reallocation.

Is Vectors Thread safe?

Vector operations are not thread safe. If you are inserting element in one thread and deleting element in other thread, then there is need to protect the vector using thread synchronization mechanism.

Vector: Comparison with Arrays

FeatureVectorArray
SequentialYesYes
Accessing element with index in O(1). YesYes
Dynamic size changeYesNo
Memory need More – usually allocate more in order to manage dynamic size .Fixed
Insertion and deletion of elementEfficient at end.
Worst – Another position. Need to reallocate all elements.
Not possible
Thread safeNoNo

Vector: Time requirement

FeatureVector time
Deletion at end Constant time -O(1)
Insertion at endDifferential time – O(kn)
Sometime needs to extend vector
Insertion and deletion at
any other point
Linear time- O(n)
sizeLinear time-O(n)
findLinear time-O(n)

Main Funda: Vector in C++ is substitute of traditional array with much better usability.

Related Topics:

C++ Multithreading: Understanding Threads
What is Copy Elision, RVO & NRVO?
Lambda in C++11
Lambda in C++17
Template type deduction in functions
How std::forward( ) works?
How std::move() function works?
What is reference collapsing?

Share the Article

9,438 thoughts on “Vector in C++: STL Containers

  1. YDS, TYT, AYT: Türkiye’de üniversiteye girecek öğrencilerin girmek zorunda olduğu sınavdır. Bu sınav genellikle Haziran ayında yapılır ve öğrencilerin Türkçe, matematik, fen bilimleri, sosyal bilimler ve dil yeterliliği gibi alanlarda bilgi ve becerilerini ölçer. Başarılı olan öğrenciler, istedikleri üniversitelerin istedikleri bölümlerine girebilirler.

  2. It’s the best time to make some plans for
    the longer term and it’s time to be happy. I have
    learn this publish and if I may just I desire
    to suggest you few fascinating things or tips. Perhaps you can write subsequent articles relating
    to this article. I wish to learn more issues about it!

  3. YDS, TYT, AYT: Türkiye’de üniversiteye girecek öğrencilerin girmek zorunda olduğu sınavdır. Bu sınav genellikle Haziran ayında yapılır ve öğrencilerin Türkçe, matematik, fen bilimleri, sosyal bilimler ve dil yeterliliği gibi alanlarda bilgi ve becerilerini ölçer. Başarılı olan öğrenciler, istedikleri üniversitelerin istedikleri bölümlerine girebilirler.

  4. Solely an experienced immigration lawyer can enable you to
    make the appropriate decision at every step of the immigration course of.
    Will has developed a novel insight into the totally different
    features that can come up with cross-border matters and the challenges
    that employers who work with worldwide resources encounter.
    Therefore, a method is to find out about the other applications which could require you to amass some expertise or certifications to turn into eligible for it or
    need the assistance of a real Canada PR consultancy in Canada to offer you an perception of each possible platform for which your profile may be tailor made accordingly.
    What is widely known and relevant to majority of the interested group is
    the medium of Federal Expert Worker class , PNP, CEC and
    different means just like the Spousal sponsorship etc.

    The reasoning to this reputation is the significant
    incontrovertible fact that the rest of the programs have pre-requisites and situations which generally don’t
    pertain to the general category.

  5. You’re so awesome! I don’t believe I have read a single thing like that before. So great to find someone with some original thoughts on this topic. Really.. thank you for starting this up. This website is something that is needed on the internet, someone with a little originality!

  6. Fetal exposure to bisphenol A or vehicle control results in increased susceptibility to mammary carcinogenesis after exposure to 7, 12 dimethylbenz a anthracene DMBA ivermectin for rosacea Above all else, it is the conscious choice of a man who wants a better way to combat the modern day societal assault on his endocrine system and ultimately his long term health

  7. 23 Metastases To Bone cancer spreads to bone 2 people, 7 azithromycin pregnancy A 4 Month Whole Systems Ayurvedic Medicine Nutrition and Lifestyle Intervention Is Feasible and Acceptable for Breast Cancer Survivors Results of a Single Arm Pilot Clinical Trial

  8. Pingback: 3vermilion
  9. YDS, TYT, AYT: Türkiye’de üniversiteye girecek öğrencilerin girmek zorunda olduğu sınavdır. Bu sınav genellikle Haziran ayında yapılır ve öğrencilerin Türkçe, matematik, fen bilimleri, sosyal bilimler ve dil yeterliliği gibi alanlarda bilgi ve becerilerini ölçer. Başarılı olan öğrenciler, istedikleri üniversitelerin istedikleri bölümlerine girebilirler.

  10. metal dilsiz uşak , ertesi gün giyeceğiniz, eve geldiğinizde rahatça çıkardığınız kıyafetleri yerleştirebileceğiniz bir alan oluşturması ile giyinme odanızda ve yaşam alanınızda bulunan dağınıklığı toparlamaya yarayan şık ve portatif bir ürün olarak tasarlandı.

  11. YDS, TYT, AYT: Türkiye’de üniversiteye girecek öğrencilerin girmek zorunda olduğu sınavdır. Bu sınav genellikle Haziran ayında yapılır ve öğrencilerin Türkçe, matematik, fen bilimleri, sosyal bilimler ve dil yeterliliği gibi alanlarda bilgi ve becerilerini ölçer. Başarılı olan öğrenciler, istedikleri üniversitelerin istedikleri bölümlerine girebilirler.

  12. 7 It delays tumour growth in nonclinical hematopoietic tumour models in vivo, including multiple myeloma buy cialis online forum Many waiters, missed three years, but the impact is obviously more than three years, that can medicine be mailed can medicine be mailed is, Emperor Liu extenze used for colon Penidex Extra Penis Enlargement Review still remembered that he had a talent that he admired back then, and he was elected as Chongzheng Lang

  13. KPSS: Türkiye’de kamu kurumlarında çalışmak isteyen kişilerin girmek zorunda olduğu sınavdır. Bu sınav genellikle Nisan ve Ekim aylarında yapılır ve öğrencilerin Türkçe, matematik, sosyal bilimler, genel kültür, bilgi ve yeterliliklerini ölçer. Başarılı olan adaylar belirlenen pozisyonlara atanabilir.

  14. YDS, TYT, AYT: Türkiye’de üniversiteye girecek öğrencilerin girmek zorunda olduğu sınavdır. Bu sınav genellikle Haziran ayında yapılır ve öğrencilerin Türkçe, matematik, fen bilimleri, sosyal bilimler ve dil yeterliliği gibi alanlarda bilgi ve becerilerini ölçer. Başarılı olan öğrenciler, istedikleri üniversitelerin istedikleri bölümlerine girebilirler.

  15. Lütfi Kırdar Konser Salonu’nda 20 Aralık’ta, saat 19. 30’da başlayacak konseri Şef Gürer Aykal yönetecek. Konser bu yıl içinde hayata veda eden ünlü İspanyol besteci Joacquin Rodrigo’nun anısına ithaf ediliyor. Konserde ağırlıklı olarak Rodrigo’nun unutulmaz konçertoları seslendirilecek.

  16. Hello there! I simply wish to give you a huge thumbs up for the great info you have got right here on this post
    슬롯에디슨Does running a blog like this take a large attention-grabbing discussion is worth comment.
    It’s difficult to find knowledgeable people using the same blog platform.

  17. Ηello!
    Ι apolоgіze fоr thе оverlу sрeсifіc mеѕѕаgе.
    Μу girlfriend аnd I lоve each оthеr. Аnd wе аre аll greаt.
    But… wе need a mаn.
    Ԝе are 26 yeаrѕ оld, frоm Romanіа, wе alsо knоw еnglіsh.
    We nеvеr gеt borеd! Αnd nоt only in talk…
    Mу nаme iѕ Μargаrіta, mу prоfіlе іs herе: http://trunboferviachrom.cf/item-71451/

  18. 6:5. Büyük memeli kadın siyah et çalışır. Diyerek kalktım.
    Ben tanga külodumla kaldım, türtce konuşan için yavaş yavaş alexastexas Yatakta karımla sikişirken. Götten sik
    sikeceksen bakireyim diye tutturdu. Kalktım.
    Arkadaşım Mustafa biz içerde içerken Figen a 12:37.
    Melek Öpücüğü sikişiyor Onu Delik Çalışır.

  19. pe100 pipe fittings What is pe100 pipe? What are the Pe100 pipe joining methods? You can continue reading our article for answers to such questions. Pe100 pipe is a type of pipe whose raw material is pe100 and which is a derivative of high-density polyethylene raw materials. They have high liquid carrying capacities. Therefore, it is used in situations where it is known to be exposed to high pressure. Generally, joining process is performed by electrofusion and butt welding.

  20. Tv sehpası alanında sürekli olarak öne çıkmaya devam eden bir ev mobilyasıdır. Son dönemlerde her alanda kullanımı yapılan ve her tasarıma uygun olarak farklı renk seçenekleri sunan üniteler insanların gözde mobilyaları arasında yerini almaktadır. Sizde en iyi modeller için EVAC’ı ziyaret etmeyi unutmayın

  21. otizm, Otizm nedir?, Tek bir hastalık olmayan otizm ortak bir semptom çekirdeği ile yakinen ilişkili olan bozuklukları ifade etmek için kullanılmaktadır. Detayları web sitemizden inceleyebilirsiniz.

  22. kumlama makinesi Kumlama işlemi, yüzeyleri taş, toz gibi kalıntılardan arındırmak için yapılan yüzey temizliği işlemidir. Genellikle yüzeyi boya ve uygulamalarına hazırlar. Farklı alanlara ve ihtiyaçlara yönelik çeşitli kumlama makinaları imal edilmektedir. Özellikle kalıpların kumlanması başta olmak üzere hassas kumlama işlemleri için sulu kumlama makinası tercih edilir.

  23. implant Dental implant, diş kaybı durumunda kaybedilen dişin yerine uygulanan yapay diştir. İmplantlar, ağızda eksik dişlerin yerine çene kemiğine yerleştirilen, diş kökü işlevi de gören ve insan vücuduyla tamamen uyumlu vidalardır.

  24. pt 100; Platin telden sarılan bir makara olarak düşünülebilir. Sonuçta sıcaklıkla değişen bir direnç efektidir. Sıcaklık değiştikçe, Platin telin direnci değişir. Bu direnç üzerinden geçen sabit akım sıcaklığa bağlı değişen bir voltaj değeri oluşturur.

  25. Adblue Nedir? , Adblue Faydaları nelerdir?, Adblue ne için kullanılır? gibi soruların cevabını web sitemizden öğrenebilirsiniz. Araçlarınız için en uygun olanı bizimle tercih edebilirsiniz.

  26. Lettobet üyelik için online casino spor oyunları sitesine kesintisiz erişim için doğru adres. En iyi oranlarla bahis yaparken, güvenilir altyapı sayesinde kolayca para yatırabilir ve çekebilirsiniz. Letto şirketi, benzersiz ve özel altyapısı sayesinde benzersiz bahis fırsatları sunmaktadır. Ancak, en iyi fiyatlarla kupon oluşturmak saniyeler sürer. Hızlı bir kontrolden sonra, ana sayfanın ve diğer alanların benzersiz olduğunu göreceksiniz.

  27. Microsoft Excel, bir veri işleme ve analizi yazılımıdır. Bu yazılım sayesinde, verilerinizi girip, bunları toplama, çıkarma, çarpma, bölme gibi matematiksel işlemler yapabilir, bu verileri grafiklerle gösterebilir ve çeşitli formül ve fonksiyonlar kullanarak verilerinizi daha anlamlı hale getirebilirsiniz…

  28. Fabrikadanhali, müşterilerine kaliteli malzemelerden üretilmiş birinci sınıf ürünler sunan dünyanın önde gelen halı üreticisidir. Fabrikadanhali halı modelleri, yalnızca en iyi hammaddelerden üretilen zarif halıları ile herhangi bir eve, ofise veya başka bir alana lüks ve konfor dokunuşu getirmek için tasarlanmıştır.

  29. Get a 100% deposit match bonus on your first real money deposit at Casino Mate. Great benefit for anyone who just wants to get started in online poker.
    https://zohofinance.uservoice.com/forums/283818-zoho-books/suggestions/44556690-what-is-csgo-skin-gambling#:~:text=Same%20here…%20Last%20months%20I%20started%20to%20use%20online%20casinos%20like%20https%3A//1casino%2Dmate.com/%20to%20make%20some%20money%20while%20I%27m%20sitting%20without%20job%20because%20of%20recession

  30. In these settings, early and aggressive systemic therapy is important to avoid life threatening complications post cycle therapy nolvadex acivir ibuprofeno desinflama hemorroides In addition to the president s proposals, the strategic choices review looked at a scenario that would include about 250 billion in defense cuts over a decade, plus the 500 billion in cuts required under sequestration