Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Intermediate
Sep 21, 2004



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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 <vector>
using namespace std;

class SomeObject
   int myData;

void main(void)
   vector<int> listOfInts(15);  // creates an array that can store 15 ints
   vector<char> listOfChars(20, 'a');   // creates an array of 20 a's
   vector<SomeObject> 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
Sophy Pal
Thanks for your registration, follow us on our social networks to keep up-to-date