5

I am trying to compile some C++ code (which can be compiled with Visual Studio 2012 on Windows) with g++-4.4.

I have this snippet of code,

const std::string cnw::restoreSession(const std::vector<string> &inNwsFile) {
   for (std::string &nwFile : inNwsFile){
       // some...
   }
}

that I cannot compile because of this error:

CNWController.cpp:154: error: expected initializer before ‘:’ token

Can you give me some advise on how to solve this problem?

David G
  • 94,763
  • 41
  • 167
  • 253
Aslan986
  • 9,984
  • 11
  • 44
  • 75

1 Answers1

13

Your compiler is too old to support range-based for syntax. According to GNU it was first supported in GCC 4.6. GCC also requires you to explicitly request C++11 support, by giving the command-line option -std=c++11, or c++0x on compilers as old as yours.

If you can't upgrade, then you'll need the old-school equivalent:

for (auto it = inNwsFile.begin(); it != inNwsFile.end(); ++it) {
    std::string const &nwFile = *it; // const needed because inNwsFile is const
    //some...
}

I believe auto is available in GCC 4.4 (as long as you enable C++0x support), to save you writing std::vector<string>::const_iterator.

If you really do need a non-const reference to the vector's elements then, whichever style of loop you use, you'll need to remove the const from the function parameter.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644