Solved

Accessing of objects in an array

Posted on 2004-08-16
4
216 Views
Last Modified: 2012-05-05
I have an template which is an array that stores objects. To display all the objects of the array I wrote a code it is not working.  The code is as below. The displaying of the trucks is written in Agency class.

cout<<trucks; //code to display the trucks


trucks is a template of array to store trucks

FlexArray<Trucks*> trucks;// declaration of trucks template.(this declaration is also done in agenct class only)

The code for trucks and the template(Flexarray) is as below.
/////////////////////////////////////trucks.cpp//////////////////////////////////////////////////////////////

#include "Trucks.hpp"

Trucks::Trucks(char *a,int b,int c,bool avail)
{
      int len;
      len = strlen(a);

    Truck_Name = new char[len+1];
      
      strcpy(Truck_Name,a);
      Year=b;
      VIN=c;
      Available=avail;
}
      
Trucks::~Trucks()
{
   clog<<"Deleted Truck"<<Truck_Name<<endl;
   delete Truck_Name;

}

ostream& Trucks::print(ostream& out)
{
    if(Available)
            out<<setw(10)<<VIN<<setw(20)<<Truck_Name<<setw(10)<<Year<<setw(6)<<"Yes"<<endl;
      else
        out<<setw(10)<<VIN<<setw(20)<<Truck_Name<<setw(10)<<Year<<setw(6)<<"No"<<endl;
    return out;
}


////////////////////////////////flexarray.hpp/////////////////////////////////////////////////////////////////////

#ifndef FLEX
#define FLEX
 // ==========================================================================
 // Template declaration for a flexible array of base type T.

 #include "tools.hpp"
 #define FLEX_START 4 // Default length for initial array.

 template <class T>
 class FlexArray {
 private:// ---------------------------------------------------------------
 int Max;                  // Current allocation size.
 int N;                        // Number of array slots that contain data.
 T* Data;                  // Pointer to dynamic array of T.

 void grow(void);            // Double the allocation length.

 public: // ---------------------------------------------------------------
 FlexArray( int ss = FLEX_START ) : Max(ss), N(0), Data( new T[Max] ) {}
 //~FlexArray() { if (Data != NULL) delete[] Data; }
 ~FlexArray() { for (int i=0; i<N; i++) delete Data[i]; }

 int put( T data );
 const T find(int id){
       for(int i=0; i<N; ++i) {if(*Data[i]==id) return Data[i];}
       return NULL;

 }

 const T find(char* nm){
       for(int i=0; i<N; ++i) {if(*Data[i]==nm) return Data[i];}
       return NULL;

 }
 
T remove(int id)
{
      T temp;

      for(int i=0;i<N; i++)
      {
            if(*Data[i]==id) {temp=Data[i]; Data[i]=Data[--N]; delete temp;}
      }

      return NULL;
}

 T& operator[]( int k );

 int data_size() {return N;}

 T* extract() { T* tmp=Data; Data=NULL; Max = N = 0; return tmp; }
 ostream& print( ostream& out ) const
 {
      for (int k=0; k<N; ++k) out << Data[k] <<endl;
      return out;

 }
 };
 template <class T> inline ostream&
 operator<< ( ostream& out, FlexArray<T>& bp){ return bp.print(out); }

template <class T> int
 FlexArray<T>::put( T data ){
 if ( N >= Max ) grow(); // Create more space if necessary.
                        
 Data[N]= data;
 return ++N;            // Return subscript at which item was stored.
 }

 //------------------------------------------- access the kth T in the array.
 template <class T> T&
 FlexArray<T>::operator[]( int k ) {
 if ( k >= N ) fatal( "Flex_array bounds error." );
 return Data[k];      // Return reference to desired array slot.
 }

 // ------------------------------------- double the allocation length.
 template <class T> void
 FlexArray<T>::grow()
 {
      T* temp = Data;    // hang onto old data array.
      Max*=2 ;
      Data = new T[Max]; // allocate a bigger one.
      memcpy(Data, temp, N*sizeof(T)); // copy info into new array.
      delete temp;            // recycle (free) old array.
 }                  
 
#endif

0
Comment
Question by:rmvprasad
4 Comments
 
LVL 12

Expert Comment

by:andrewjb
ID: 11818409
Give us a clue. In what way doesn't it work?
0
 
LVL 4

Expert Comment

by:smpoojary
ID: 11818797
Don't show your actual code. Becuase we have no patience to read it.  
Please convert it to a simple example. After clear this simple example then you can convert it to your actual project code.

Let me know simple example for your doubt.
0
 
LVL 17

Expert Comment

by:rstaveley
ID: 11820421
You have an array of pointers to objects. That means that T is of type Trucks*.

You find the object with one of the following:
--------8<--------
//...
const T find(int id){
      for(int i=0; i<N; ++i) {if(*Data[i]==id) return Data[i];}
      return NULL;
 }
const T find(char* nm){
      for(int i=0; i<N; ++i) {if(*Data[i]==nm) return Data[i];}
      return NULL;

 }
--------8<--------

That means that you would need to have Trucks::operator==(int) or Trucks::operator==(const char*) defined, which I do not see in your Trucks class definition. In any case I don't believe that it would be good style to have one of these defined.

May I suggest you take a step back and reconsider your design.

Is this an academic assignment or can you consider using a standard library container?
0
 
LVL 39

Accepted Solution

by:
itsmeandnobodyelse earned 50 total points
ID: 11821163
>> FlexArray<Trucks*> trucks

When using Trucks* as an template argument, you try to print a pointer Data[k] with that

    for (int k=0; k<N; ++k) out << Data[k] <<endl;

So you should change your array to

    FlexArray<Trucks> trucks;

However, after this you need a copy constructor as the array holds copies of Trucks objects

   Trucks::Trucks(const Trucks& tr)
         : Year(tr.Year), VIN(tr.VIN), Available(tr.Available) {}

Also, you need an operator<<  (instead of print), an operator = (to assign Trucks objects) and an operator == (to compare array objects with search object).

operator<< function normally is declared  as friend in class Trucks

    class Trucks
    {

            ...
    public:
            friend ostream& operator << (ostream& os, const Trucks& tr);
            ...
    };

and defined like that:

      ostream& operator<<(ostream& os, const Trucks& tr)
      {
             tr.print(os);
             return os;
      }

The other operator functions you should be able to implement yourself.

Regards, Alex
0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
TTimer no longer functioning 7 90
ADO Memory leak with DELPHI 2007 37 181
mixing C++ & C# in Vis Studio 2013 7 169
How to print into std::string like sprintf using C++11? 12 59
Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…

813 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now