简体   繁体   English

列表初始化器

[英]List initializer

I am trying to declare an iterator of type std::initializer_list as it is described in this answer . 我试图声明一个类型为std::initializer_list的迭代器,如本答案所述

But I always get this error: 但是我总是会收到这个错误:

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

How do I declare an iterator of type std::initializer_list ? 如何声明类型为std::initializer_list的迭代器?

The following code for example will not work. 例如,以下代码将不起作用。 In addition, the compiler that I use supports the 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;
}

You need to add 您需要添加

#include <initializer_list>

and for this example probably also 在这个例子中

#include <iostream>

Also make sure you are using the -std=c++0x switch to g++. 还要确保您正在使用-std=c++0x切换到g ++。 And you need at least g++ version 4.4. 而且您至少需要g ++ 4.4版。 When using the compiler from MacPorts, the compiler is called g++-mp-4.5 or g++-mp-4.4 . 从MacPorts使用编译器时,编译器称为 g++-mp-4.5g++-mp-4.4 (Incorrect assumption). (错误的假设)。

I noticed some recently fixed bugs related to initializer_list on the GCC bugzilla , so I recommend getting the newest version of GCC, 4.5.1. 我在GCC bugzilla上注意到了一些与initializer_list相关的最近已修复的错误,因此,我建议获取最新版本的GCC 4.5.1。 Because when using this version I am able to compile both your examples without problems. 因为使用此版本时,我可以毫无问题地编译两个示例。

Your compiler's implementation probably just doesn't have these typedefs (eg with GCC 4.4.1, initializer_list doesn't contain any typedefs, you can check the header yourself). 您的编译器的实现可能只是没有这些typedef(例如,在GCC 4.4.1中, initializer_list不包含任何typedef,您可以自己检查标头)。

As a "workaround", use auto : 作为一种“解决方法”,请使用auto

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

Or rely on initializer_list<T>::iterator being a synonym for const T* . 或依靠initializer_list<T>::iterator作为const T*的同义词。

You can avoid directly specifying the iterator type, 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"));
}

Range-based for loops are supported in GCC 4.6 . GCC 4.6支持基于范围的for循环。 (Any problem calling them foreach loops, informally?) (是否有非正式地将它们称为foreach循环的问题?)

Including <iterator> may be required for std::begin and std::end, though several headers guarantee they are declared (24.6.5, N3092). std :: begin和std :: end可能需要包含<iterator>,尽管可以保证声明了多个标头(24.6.5,N3092)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM