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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…