Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: c++ question, auto x doesn't work.  (Read 1740 times)

0 Members and 1 Guest are viewing this topic.

paupav

  • Full Member
  • ***
  • Posts: 156
    • View Profile
    • Email
c++ question, auto x doesn't work.
« 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?
« Last Edit: July 11, 2014, 11:34:55 am by paupav »

Laurent

  • Administrator
  • Hero Member
  • *****
  • Posts: 32504
    • View Profile
    • SFML's website
    • Email
Re: Why this doesn't work
« Reply #1 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).
« Last Edit: July 11, 2014, 11:18:09 am by Laurent »
Laurent Gomila - SFML developer

Strelok

  • Full Member
  • ***
  • Posts: 139
    • View Profile
    • GitHub
Re: c++ question, auto x doesn't work.
« Reply #2 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;
 
« Last Edit: July 11, 2014, 11:49:00 am by Strelok »

Jesper Juhl

  • Hero Member
  • *****
  • Posts: 1405
    • View Profile
    • Email
Re: c++ question, auto x doesn't work.
« Reply #3 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
$