这个(auto && elem:v)语法是简单的C++吗?我应该使用什么编译器来编译它?

J. *_*mel -5 c++ iterator compilation set

我曾经在12年前使用C++编写代码,但由于我的工作原因,我把它留给了其他更简单的语言.

我想更新我的知识并尝试编译这里提出的解决方案,只是为了尝试这种迭代向量的新方法.但遇到编译错误:

expected initializer before ‘:’ token

我不知道有可能避免显式声明迭代器,就像C++使用它一样(auto && elem : v).C++它的版本是什么?

b.cpp

#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>
#include <string>
#include <set>

int main()
{
  std::vector<std::pair<std::string, std::string>> v
  {   {"handgun", "bullets"},
      {"turret", "bullets"}};

  std::cout << "Initially: " << std::endl << std::endl;
  for (auto && elem : v)
    std::cout << elem.first << " " << elem.second << std::endl;

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

汇编

$ cc b.cpp  -std=c++0x  -o myprog
Run Code Online (Sandbox Code Playgroud)

错误

b.cpp:在函数'int main()'中:
b.cpp:15:错误:在':'标记之前的预期初始化程序
...

我使用的C++编译器: g++

$ g++ --version
Run Code Online (Sandbox Code Playgroud)

g++ (GCC) 4.4.7 20120313 (Red Hat 4.4.7-3)
Copyright (C) 2010 Free Software Foundation, Inc.
Run Code Online (Sandbox Code Playgroud)

uh *_*per 9

你的编译器太旧了.基于范围的循环直到4.6才添加. for

另外,忽略评论.cc通常符号链接到gcc.从手册:

GCC识别具有这些名称的文件并将它们编译为C++程序,即使您以与编译C程序相同的方式调用编译器(通常使用名称gcc).

  • @ user2079303 A)真正的问题是OP的编译器太旧了.B)基于Ranged的for循环是一种语言结构,它们不需要`libstdc ++`来工作. (2认同)