Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

c++ - 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

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...