Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
306 views
Welcome To Ask or Share your Answers For Others

1 Answer

Usually, the first thing I do with argc and argv is this:

std::vector<std::string> arguments(argv, argv + argc);

Now I have a vector of strings to work with and I can easily use not only the range-based for loops, but also C++ standard library facilities.

for(std::string& s : arguments) {
    // do stuff...
}

The wikipedia code works because the type of my_array is a variable of array type. The original code does not work, because argv is not an array. The syntax char* argv[] may make it look like it is an array, but that's just a sad artifact of C syntax. char* argv[] is exactly the same as char** argv. argv is not an array; it's actually just a pointer.

The range-based for loop works on:

  • arrays;
  • any type that has member functions begin() and end() that return iterators;
  • any type for which exist non-member functions begin and end that can be called like begin(x) and end(x), with x being the thing that you're iterating over.

As you can see, pointers are not part of this list.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...