List initializer

I am trying to declare a type iterator std::initializer_listas described in this answer .

But I always get this error:

error: 'iterator' is not a member of 'std::initializer_list<int>'

Can someone tell me how to declare a type iterator std::initializer_list?

EDIT:

This code, for example, will not work. In addition, the compiler I'm using supports a new standard draft

int findCommon(std::initializer_list<int> nums)
{
    std::initializer_list<int>::iterator it;
    for (it = nums.begin() ; it != nums.end() ; ++it)
    {
        std::cout << *it << std::endl;  
    }
    return 1;
}
+3
source share
3 answers

You need to add

#include <initializer_list>

and for this example, probably also

#include <iostream>

Also make sure you use the switch -std=c++0xin g ++. And you need at least g ++ version 4.4. When using the compiler from MacPorts, the compiler is called g++-mp-4.5or g++-mp-4.4. (wrong assumption).

, initializer_list GCC bugzilla, GCC, 4.5.1. .

+3

, , typedef (, GCC 4.4.1, initializer_list - typedefs, ).

" ", auto:

int findCommon(std::initializer_list<int> nums)
{
    for (auto it = nums.begin() ; it != nums.end() ; ++it)
    {
        std::cout << *it << std::endl;
    }
    return 1;
}

initializer_list<T>::iterator, const T*.

+1

You can avoid directly specifying the type of iterator, which should lead to cleaner code:

void f(std::initializer_list<int> nums)
{
  for (auto x : nums) {
    std::cout << x << '\n';
  }
  // or:
  std::copy(begin(nums), end(nums), std::ostream_iterator(std::cout, "\n"));
}

The range for loops is supported in GCC 4.6 . (Any problem causing their foreach loops informally?)

The inclusion of a <iterator> may be required for std :: begin and std :: end, although some headers guarantee that they are declared (24.6.5, N3092).

0
source

Source: https://habr.com/ru/post/1766756/


All Articles