Pat*_*ryk 4 for-loop range c++11
我想尝试基于c ++ 11 range-based for loop,char* argv[]但是我遇到了错误.目前的方法是:
for( char* c : argv )
{
printf("param: %s \n", c);
}
Run Code Online (Sandbox Code Playgroud)
在我的makefile中,我有以下行:
g++ -c -g -std=c++11 -O2 file.cc
Run Code Online (Sandbox Code Playgroud)
argv 是指向原始字符串的指针数组,您无法直接从中获取范围.
您可以将其转换为动态std::vector<std::string>,与for-range循环一起使用:
#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());
}
}
Run Code Online (Sandbox Code Playgroud)
这使用了std::vector构造函数#4:
template< class InputIt >
vector( InputIt first, InputIt last,
const Allocator& alloc = Allocator() );
Run Code Online (Sandbox Code Playgroud)
使用范围的内容构造容器
[first, last).[...]