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: 13
  • 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? 3
  • +

Replies To: Store Class Objects in vector

#2 skaoth  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 91
  • 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: 13
  • 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: 3
  • 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
  • +
  • -

#6 ciccioriccio  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 07-June 12

Posted 07 June 2012 - 09:34 AM

I'm a newby of C++ and I've found very useful this tutorial. But
it should be useful (if it's possible) to show how to access in a random way to one element of the structure. Suppose there are ten friends recorded in the list and I wan to the data of the fifth element. How to?
Thanks in advance.

Ciccioriccio
Was This Post Helpful? 0
  • +
  • -

#7 evian  Icon User is offline

  • New D.I.C Head

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

Posted 07 June 2012 - 05:07 PM

Hi-

You'd want to create getter functions in the class to access the data located in the private class variables stored within the vector, to pass it into the main program . The code contains class setter methods already in the form of setName, setAge, setHeight- this is how it passes the information from the user and to the private class variables. Now, you need the data to go the other way after it's been stored. So, you'd create a getter function in the "public" portion of the class code, just like the setter functions are already declared. A sample getter function would look like:
string getName { return name; }


You have to declare one for each private class variable you want to retrieve data from. And then to access specific elements of the stored info in the vector in a random fashion, you'd give the below command in the main program, below the part where you input all the user info:
cout << list.at(n).getName(); //where "n" is the vector index position you wish to access


What you're doing is accessing the vector named "list" at a specific index position and calling the getName function to access the specific data stored at that position (in this example, you have three pieces of data stored at that index position). Just remember that vector index numbering starts at 0 and not 1, so to call the first record you'd access index position 0. Hope that helps!

Evan

View Postciccioriccio, on 07 June 2012 - 09:34 AM, said:

I'm a newby of C++ and I've found very useful this tutorial. But
it should be useful (if it's possible) to show how to access in a random way to one element of the structure. Suppose there are ten friends recorded in the list and I wan to the data of the fifth element. How to?
Thanks in advance.

Ciccioriccio

Was This Post Helpful? 0
  • +
  • -

#8 ciccioriccio  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 07-June 12

Posted 08 June 2012 - 12:51 AM

Hi, Evan
Thank you for your useful answers. As soon as possible I'll try your suggestions. It seems to me that the scope of the code of Mr. Nirvanarupali is to show an elegant method to manage data in a structure with vector. In this case it should be useful to complete the dissertation with an example about random access.
Ciccioriccio
Was This Post Helpful? 0
  • +
  • -

#9 evian  Icon User is offline

  • New D.I.C Head

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

Posted 08 June 2012 - 05:59 AM

Ciccioriccio,

No problem- you're right that it would've been useful if an example had been provided about random access, but, then again, the title of this discussion was "Storing Class Objects in Vector," not "Retrieving Class Objects in Vector," so more emphasis was placed on the former. :) And, besides, once you've implemented all the code necessary to create the class and store the code, it's very simple to implement the random access part...

Evan

View Postciccioriccio, on 08 June 2012 - 12:51 AM, said:

Hi, Evan
Thank you for your useful answers. As soon as possible I'll try your suggestions. It seems to me that the scope of the code of Mr. Nirvanarupali is to show an elegant method to manage data in a structure with vector. In this case it should be useful to complete the dissertation with an example about random access.
Ciccioriccio

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1