Re: stl vector find.

From: Karl Heinz Buchegger (kbuchegg_at_gascad.at)
Date: 01/28/04


Date: Wed, 28 Jan 2004 11:27:30 +0100

Dark Alchemist wrote:
>
> Once I can understand this part another problem I see is in the naming
> of the structures since I might have 1 or I might have 100 or even 1000.
> So, in essence I need to dynamically name my structures but for now the
> main issue is understanding how to achieve the above.
>
> struct Entry
> {
> std::string keyword;
> std::string helptext;
> int cost;
> std::string current_spell;
> int school;
> int itemtype;
> int hiddenstatus;
> };
>
> Maybe if I knew how to dynamically name my structures the rest will fall
> into place (like adding a vector of structs for spell, school,
> itemtype).

I don't know what you mean with 'dynamically name my structure'
although I have a guess.

I think you are fighting with: how to come up with n object
(of type Entry) on the fly when I need one. The simple solution
is don't. Vector handles all of this.

Your reading loop will look something like this:

  std::string Line;

  while( getline( in, Line) ) { // read entire line
    //
    // break the read line into parts
    //
    std::stringstream LineStream( Line );

    std::string keyword;
    std::string helptext;
    int cost;
    char Bar1, Bar2, Bar3, Bar4, Bar5, Bar6;

    LineStream >> keyword >> Bar1 >> helptext >> Bar2 >> cost >> ....

    //
    // create new object of type Entry and fill it with
    // the values read from the file
    //

    Entry NewEntry;
    NewEntry.keyword = keyword;
    NewEntry.helptext = helptext;
    NewEntry.cost = cost;

    //
    // and tell the vector to add such a thing
    //
    // MyKeys is of type std::vector< Entry >
    //
    MyKeys.push_back( NewEntry );
  }

the vector will allocate a new entry and copy the passed data to
this new entry.

Simplifications are of course possible by introducing a constructor
for Entry, but I left that out intentionally. I think you first
should grasp the power that a struct gives to you in comparison
to having lots of individual arrays.

-- 
Karl Heinz Buchegger
kbuchegg@gascad.at


Relevant Pages