Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 experiments, why can't I use some of the features?

Tags:

c++

c++11

I'm currently overviewing the new features of C++11 and for currently ununderstood reasons, some of them does not compile. I use gcc version 4.6.0 20100703 (experimental) (GCC) so according to the GNU GCC FAQ, all features I tried are supported . I tried to compile with both of std=c++0x and std=gnu++0x flags.

Non member begin() & end()

For instance, I wan't to use non member begin() and end(), in piece of code like :

#include <iostream>
#include <map>
#include <utility>
#include <iterator>

using namespace std;
int main ( ) {
    map < string, string > alias;
    alias.insert ( pair < string, string > ( "ll", "ls -al" ) );
    // ... Other inserts

    auto it = begin(alias);
    while ( it != end(alias) ) {
        //...
    }

And I get,

nonMemberBeginEnd//main.cc:15:24: error: ‘begin’ was not declared in this scope
nonMemberBeginEnd//main.cc:15:24: error: unable to deduce ‘auto’ from ‘<expression error>’ // Ok, this one is normal.
nonMemberBeginEnd//main.cc:16:26: error: ‘end’ was not declared in this scope

Do I need to include special headers ?

For range

My second (and last) question is weirder because It cannot depend on black magic hidden header that I might had not included.

The following code :

for ( auto kv : alias )
    cout << kv.first << " ~ " << kv.second << endl;

Give me the following errors :

rangeFor/main.cc:15:17: error: expected initializer before ‘:’ token

I hope my questions are not off topic or too rookie for you guys and you'll help me find out what's wrong :D

like image 525
Maxime Avatar asked Nov 01 '11 18:11

Maxime


1 Answers

It works on gcc 4.6.1:

#include <iostream>
#include <map>
#include <string>

int main(int argc, char** argv) {
    std::map<std::string, std::string> alias = {{"key", "value"}};
    for (auto kv: alias)
        std::cout << kv.first << " ~ " << kv.second << std::endl;

    auto it = begin(alias);
    while (it != end(alias) ) {
        std::cout << (*it).first << " ~ " << (*it).second << std::endl;
        it++;
    }
    return EXIT_SUCCESS;
}

And the result:

# /opt/gcc-4.6.1/bin/g++-4.6 --std=c++0x test.cc -o test && ./test
key ~ value
key ~ value
like image 153
fsaintjacques Avatar answered Sep 17 '22 21:09

fsaintjacques