How to execute a C ++ 11 range for a loop on char * argv []?

I would like to try C ++ 11 for a loop on char* argv[], but I am getting errors. According to the current approach:

for( char* c : argv )
{                                                                                               
   printf("param: %s \n", c);                                                                    
}

and in my makefile I have the following line:

g++ -c -g -std=c++11 -O2 file.cc
+4
source share
2 answers

argv is an array of pointers to raw strings, you cannot get a range from it directly.

You can convert it to std::vector<std::string>on the fly, which works with the for-range loop:

#include <iostream>
#include <string>
#include <vector>

int main (int argc, char const * const argv[])
{
    for (auto && str : std::vector<std::string> { argv, argv + argc })
    {
        std::cout << "param: " << str << std::endl;
        // Or, but require <cstdio>
        // std::printf("param: %s\n", str.c_str()); 
    }
}

This uses std::vectorconstructor # 4 :

template< class InputIt >
vector( InputIt first, InputIt last,
        const Allocator& alloc = Allocator() );

Creates a container with the contents of a range [first, last). [...]

+8
source

, .

( " " ), :

for (char ** p = argv, e = argv + argc; p != e; ++p)
{
    // use *p
}

:

#include <cstddef>

template <typename T>
struct array_view
{
    T * first, * last;
    array_view(T * a, std::size_t n) : first(a), last(a + n) {}
    T * begin() const { return first; }
    T * end() const { return last; }
};

template <typename T>
array_view<T> view_array(T * a, std::size_t n)
{
    return array_view<T>(a, n);
}

:

for (auto s : view_array(argv, argc))
{
    std::cout << s << "\n";
}
+2

All Articles