devxlogo

Using Vectors

Using Vectors

When you’re learning about data structures, you’ll come across a very useful class called vector. It’s basically an array, but it stores its elements dynamically. That means that it can grow infinitely or until you have no more memory.

The example below illustrates how to use this class:

#include using namespace std;class SomeObject{public:   int myData;};void main(void){   vector listOfInts(15);  // creates an array that can store 15 ints   vector listOfChars(20, 'a');   // creates an array of 20 a's   vector listOfObjects;  // default constructor   listOfInts.push_back(20);  // add 20 to the listOfInts vector   listOfChars.push_back('b');  // add 'b' to the listOfChars vector   SomeObject tempObject;  // create a temporary object   tempObject.myData = 2;  // set its member data to 2   listOfObjects.push_back(tempObject);  // adds tempObject to the listOfObjects vector}

devx-admin

Share the Post: