IAE IAE - 1 month ago 7
C++ Question

How to Write the Range-based For-Loop With Argv?

From the c++0x Wikipedia site:

int my_array[5] = {1, 2, 3, 4, 5};
for (int &x : my_array) {
x *= 2;
}


So why does this code not work?

int main(int argc, char* argv[])
{
for (char *arg : argv)
{
// Do something.
}
}


Error:

main.cpp:36: error: no matching function for call to ‘begin(char**&)’


I am using Qt with g++ 4.6.1 on Ubuntu 11.10.

Additional Information

Is There a Range Class in C++0x

Range-Based For-Loop Statement Definition Redundance

Answer

You don't, because the system can't tell how long argv is at compile time. Someone can likely find the proper section of the standard to quote you about this.

There is a way around it though, and that's to create a custom class to wrap argv. It's not even that hard.

class argv_range {
 public:
   argv_range(int argc, const char * const argv[])
        : argc_(argc), argv_(argv)
   {
   }

   const char * const *begin() const { return argv_; }
   const char * const *end() const { return argv_ + argc_; }

 private:
   const int argc_;
   const char * const *argv_;
};

Here's how you use it:

for (const char *arg: argv_range(argc, argv)) {
   // Do something.
}

Yeah, I use a lot of consts. Basically, argv is an array of character pointers, none of which should be modified, each pointing to a string, none of the characters of which should be modified either.

Comments