Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Accessing of objects in an array

Posted on 2004-08-16
4
Medium Priority
?
244 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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 200 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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.
Suggested Courses

618 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