Page 1 of 1

Store Class Objects in vector Just like making a linked list Rate Topic: -----

#1 nirvanarupali  Icon User is offline

  • D.I.C Stomach
  • member icon

Reputation: 12
  • View blog
  • Posts: 1,119
  • Joined: 01-August 07

Posted 10 September 2008 - 04:55 PM

First of all I would like to thank to Martyr2 for some guidance.

In this tutorial, I will show how to store class objects in vector just like making a linked list using the STL. A conventional linked list is a structure of data that is linked together using the struct or class keywords.

Overview of Linked List.

An array is like a tupperware, they are containers but they are fixed in size. If you choose a big container it would be a waste of storage area on the other side, if you choose a small container chances are it would spill and that would be a big mess. Before the advent of the STL containers, programmers have found ways to solve the problem and that is creating a lists.

There are tree kind of Lists.

1.)Singly List
2.)Doubly List
3.)Trees

Why Use STL?

When the STL has been standardized, the use of home-cooked containers are not anymore popular in real world problems, although these are good to learn how it works specially manipulating computer memory by using a lot of pointers. If your code has new operations, delete operations, and pointer arithmetic all over the place, you are going to mess up somewhere and get leaks, stray pointers, etc. This is true independently of how conscientious you are with your allocations: eventually the complexity of the code will overcome the time and effort you can afford. It follows that successful techniques rely on hiding allocation and deallocation inside more manageable types. Good examples are the standard containers. -Bjarne Stroustrup

Store class objects in vector

Let's go with the codes. In this example I will make Friend class to create an objects which has data such as name, age and height and store these objects in vector. The idea is similar in creating a linked list, but I will not deal with linked lists anymore for the reason that it has plenty of tutorials here on DIC or if you search in google.

class Friend
{
    public:
        Friend();
        ~Friend(){}
        void setName(string friendName){ name = friendName;}
        void setAge(int friendAge) { age = friendAge; }
        void setHeight(int friendHeight) { height = friendHeight; }
        void printFriendInfo(); 
        
    private:
        string name;
        int age;
        float height;
};
Friend::Friend()
{
    age = 0;
    height = 0.0;
}
void Friend:: printFriendInfo()
{
    cout << "Name       : " << name << endl;
    cout << "Age        : " << age << endl;
    cout << "Height     : " << height << endl <<endl;
}

A friend class is declared and has three member functions which are inlined. Each function has one parameter and is set to the corresponding variables. The last is the printFriendInfo() is used to print member data.

A constructor was made and is setting the member variables age and height to 0.

The main function.

int main()
{
   // Create a vector of Friend objects
   vector<Friend> list;
   string Name;
   int Age; 
   float Height;
   
   Friend *f1;
   
   for (int n=0; n<3; n++)
   {    
        cout <<"Enter name :"<<endl;
        getline(cin, Name);
        cout <<"Enter age :"<<endl;
        cin >> Age;
        cout <<"Enter height :"<<endl;
        cin>> Height;
        
        f1 = new Friend;
        f1->setName(Name);
        f1->setAge(Age);
        f1->setHeight(Height);
        list.push_back(*f1);
        
   }
   

   // Now setup an iterator loop through the vector
   vector<Friend>::iterator it;

   for ( it = list.begin(); it != list.end(); ++it ) {
      // For each friend, print out their info
      it->printFriendInfo();
   }

   return 0;
}


In the main function, first line is the declaration of vector Friends(empty vector). Then there are three variables were made. The for loop gives three inputs from the user, after getting age, name and height new Friend object is created and put it in vector. The loop terminates after 3 inputs. Iterator is created, to walk through the lists and it will display each object's data.

It is easy, right? Well its your turn now modifying this codes with the use of list container.

Full source codes;

/****************************************

Store class objects in vector
By: nirvanarupali

Compiled in Borland C++

*********************************************/
#include <iostream>
#include <vector>
#include <string>

using namespace std;

class Friend
{
    public:
        Friend();
        ~Friend(){}
        void setName(string friendName){ name = friendName;}
        void setAge(int friendAge) { age = friendAge; }
        void setHeight(int friendHeight) { height = friendHeight; }
        void printFriendInfo(); 
        
    private:
		string name;
        int age;
        float height;
};
//implementations
Friend::Friend()
{
    age = 0;
    height = 0.0;
}
//printing
void Friend:: printFriendInfo()
{
    cout << "Name       : " << name << endl;
    cout << "Age        : " << age << endl;
    cout << "Height     : " << height << endl <<endl;
}

int main()
{
   // Create a vector of Friend objects
   vector<Friend> list;
   string Name;
   int Age; 
   float Height;
   
   Friend *f1;
   
   for (int n=0; n<3; n++)
   {    
        cout <<"Enter name :"<<endl;
        getline(cin, Name);
        cout <<"Enter age :"<<endl;
        cin >> Age;
        cout <<"Enter height :"<<endl;
        cin>> Height;
        
        f1 = new Friend;
        f1->setName(Name);
        f1->setAge(Age);
        f1->setHeight(Height);
        list.push_back(*f1);
        cin.get(); //clear buffer
   }
   

   // Now setup an iterator loop through the vector
   vector<Friend>::iterator it;

   for ( it = list.begin(); it != list.end(); ++it ) {
      // For each friend, print out their info
      it->printFriendInfo();
   }

   return 0;
}


Is This A Good Question/Topic? 2
  • +

Replies To: Store Class Objects in vector

#2 skaoth  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 90
  • View blog
  • Posts: 601
  • Joined: 07-November 07

Posted 15 September 2008 - 11:18 PM

Quick note.

Quote

for (int n=0; n<3; n++)
{
cout <<"Enter name :"<<endl;
getline(cin, Name);
cout <<"Enter age :"<<endl;
cin >> Age;
cout <<"Enter height :"<<endl;
cin>> Height;

f1 = new Friend;
f1->setName(Name);
f1->setAge(Age);
f1->setHeight(Height);
list.push_back(*f1);

}


The fact that f1 is new'd here will cause a memory leak. You need to delete f1 after you've pushed the value into the vector. The vector will always make a copy of the value you passed in with the objects copy constructor. This is one of the reason why polymorphic types don't work with STL containers because they get sliced off by the STL container.
Was This Post Helpful? 0
  • +
  • -

#3 nirvanarupali  Icon User is offline

  • D.I.C Stomach
  • member icon

Reputation: 12
  • View blog
  • Posts: 1,119
  • Joined: 01-August 07

Posted 16 September 2008 - 01:07 AM

It depends, if you delete a node, then you use delete f1 in a specific location.
Int this example 3 objects stored in vector.

Example: f1[0] object stored and has name = Martyr2; f[1] object stored and has name=capty99; f[2] object stored and has name=skaoth.

If you delete object3 which is located at f[2], then this node is deleted.
this time use delete f1 or use erase() in STL.

This example is pattern what a linked list is. In linked list you can add a node and you can delete a node.

With regards to memory leak, in real world programs you must always use exceptions and error handling.
Was This Post Helpful? 0
  • +
  • -

#4 Guest_RJG*


Reputation:

Posted 12 February 2010 - 03:41 PM

I think the tutorial is amazingly simple and completely understandable. Thanks nirvanarupali !!
Was This Post Helpful? 0

#5 evian  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 18-November 11

Posted 18 November 2011 - 11:42 AM

Great tutorial! Very helpful! Not sure if this is improper etiquette to revive a discussion that's been inactive for so long (so sorry in advance if that's the case), or if you'll even get a notification that I've posted something (I tried to pm you but there doesn't seem to be an option to do that) here, but I was wondering how I'd go about accessing individual members of this vector of class objects you've created. For instance, how would I go about directly accessing (for modification or cout purposes) the string name variable of the second element of the vector<friend> list from outside the class, once your code's been run and the vector's been created? I've tried several things but can't seem to figure it out. Thanks in advance!

Evan
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1