Solved

Accessing of objects in an array

Posted on 2004-08-16
4
207 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Making a Sample Win32 DLL project Using Visual Studio 2010 Professional 4 91
Unresolved External Symbols 3 68
Header of docx file 17 97
FMX TCameraComponent Problem 2 50
What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

919 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

20 Experts available now in Live!

Get 1:1 Help Now