SFML community forums

Help => General => Topic started by: paupav on July 11, 2014, 11:08:37 am

Title: c++ question, auto x doesn't work.
Post by: paupav on July 11, 2014, 11:08:37 am
void print()
{
   int v[] = {0,1,2,3,4,5,6,7,8,9};

     for (auto x : v)              // for each x in v
          cout << x << '\n';

     for (auto x : {10,21,32,43,54,65})
          cout << x << '\n';
     // ...
}

It says that x doesn't have a type, but shouldn't auto give him needed type?
Title: Re: Why this doesn't work
Post by: Laurent on July 11, 2014, 11:16:17 am
We try to avoid non-SFML topics on this forum. There are other places where this kind of question would fit perfectly (stackoverflow.com, ...).

And please next time don't post on the first board that you find, read their description. The "General > General discussions" is clearly marked not being for help requests. There's a whole "Help" category below.

Another advice: use a relevant title for your problem. If everybody was using "need help" or "why this doesn't work", the forum would just be full of these vague subjects and nobody could filter what they are interested in by reading the title (which is why titles exist).
Title: Re: c++ question, auto x doesn't work.
Post by: Strelok on July 11, 2014, 11:37:45 am
It's most likely caused by the array being a raw type instead of a stl container like std::array or std::vector which have a iterator. Not 100% sure though. It works anyway
        int cArray[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        std::array<int, 9> cppArray;
        std::vector<int> cppVector;
        for (auto x : cArray)
                std::cout << x << std::endl;
        for (auto x : cppArray)
                std::cout << x << std::endl;
        for (auto x : cppVector)
                std::cout << x << std::endl;
 
Title: Re: c++ question, auto x doesn't work.
Post by: Jesper Juhl on July 11, 2014, 11:47:23 am
I don't see the problem :

$ cat foo.cc
#include <iostream>
#include <cstdlib>

int main()
{
    int v[] = {0,1,2,3,4,5,6,7,8,9};

    for (auto x : v) // for each x in v
        std::cout << x << std::endl;

    for (auto x : {10,21,32,43,54,65})
        std::cout << x << std::endl;

    return EXIT_SUCCESS;
}
$ g++ -std=c++11 foo.cc
$ ./a.out
0
1
2
3
4
5
6
7
8
9
10
21
32
43
54
65
$