Streight
Streight

Reputation: 861

arrays/lists and their dimensions

I have a problem analysing the following code:

 for (int argI = 1; argI < args_.size(); ++argI) //size(): Return the number of 
 {                                       //arguments.
      argListString += ' ';         //Space into string
      argListString += args_[argI]; //new argument into string

      if (args_[argI][0] == '-')    // ????
      {
           const char *optionName = &args_[argI][1];   //????

My problem are the lines marked with ????. When I look up the object args_ it ist of type stringList and stringList is templateclass of List<T>. List<T> ist defined as

Template<class T> 
class Foam::List< T > 
A 1D array of objects of type <T>, where the size of the vector is known and used for subscript bounds checking, etc. Storage is allocated on free-store during
construction.

So if args_ is a 1D array why is it accessed like a 2D array in line 415 and 417?

greetings streight

Upvotes: 2

Views: 60

Answers (3)

Agentlien
Agentlien

Reputation: 5116

You have a one-dimensional vector args_ where each element is of type T. Now, it would seem that this type T is a string (either a string type or a pointer to a C-style string) the elements of which can be accessed using the index operator [].

As such, it is not actually "accessed like a 2D array". Instead, each item is accessed as a one-dimensional array and the resulting object is in turned indexed.

So, assuming T is char* (which makes sense for text strings), this would make args_[argI] an element of type char* which is a pointer to a string. This string is then indexed as an array, so that args_[argsI][1] refers to the second character in the argIth string in the vector called args_.

Upvotes: 1

Mike Seymour
Mike Seymour

Reputation: 254461

Presumably, args_[argI] is a string type, and the string type overloads [] to access the characters within the string.

So this looks for options of the form -flibble; the first marked line checks whether the argument begins with -, and the second sets optionName to point to flibble.

Upvotes: 1

Sebastian Hoffmann
Sebastian Hoffmann

Reputation: 11482

It is an vector/list of strings. Strings are a sequence of chars. Thus the index operator( [] ) will likely provide access to the single chars of the string.

415 therefor checks the first char of the string and 417 accesses the substring from the second char to the end.

Upvotes: 3

Related Questions