Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


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

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
{
public:
   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
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap