如何使用Argv编写基于范围的for循环? [英] How to Write the Range-based For-Loop With Argv?

查看:112
本文介绍了如何使用Argv编写基于范围的for循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从c ++ 0x维基百科网站:

  int my_array [5] = {1,2,3,4 ,5}; 
for(int& x:my_array){
x * = 2;
}

那么为什么这个代码不起作用?

  int main(int argc,char * argv [])
{
for(char * arg:argv)
{
//做某事。
}
}

错误:

  main.cpp:36:错误:没有匹配函数调用'begin(char **&)'



我在Ubuntu 11.10上使用带g ++ 4.6.1的Qt。



信息



在C ++ 0x中有一个范围类



< a href =http://stackoverflow.com/questions/2648878/range-based-for-statement-definition-redundancy>基于范围的循环语句定义冗余

解决方案

您不需要,因为系统无法判断 argv 在编译时间有多长。有人可能会找到标准的适当部分引用你的这个。



有一个方法,但是,这是创建一个自定义类换行 argv 。这不是那么难。

  class argv_range {
public:
argv_range(int argc,const char * const argv [])
:argc_(argc),argv_(argv)
{
}

const char * const * begin ; }
const char * const * end()const {return argv_ + argc_; }

private:
const int argc_;
const char * const * argv_;
};

使用方法如下:

  for(const char * arg:argv_range(argc,argv)){
//做某事。
}

是的,我使用了很多 const s。基本上, 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

解决方案

You don't, because the system can't tell how long argv is at compile time. Someone can likely find the proper section of the standard to quote you about this.

There is a way around it though, and that's to create a custom class to wrap argv. It's not even that hard.

class argv_range {
 public:
   argv_range(int argc, const char * const argv[])
        : argc_(argc), argv_(argv)
   {
   }

   const char * const *begin() const { return argv_; }
   const char * const *end() const { return argv_ + argc_; }

 private:
   const int argc_;
   const char * const *argv_;
};

Here's how you use it:

for (const char *arg: argv_range(argc, argv)) {
   // Do something.
}

Yeah, I use a lot of consts. Basically, argv is an array of character pointers, none of which should be modified, each pointing to a string, none of the characters of which should be modified either.

这篇关于如何使用Argv编写基于范围的for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆