简体   繁体   English

back_inserter(容器)的类型是什么

[英]what is the type of back_inserter(container)

My following code compiles but I do not know how to write this without using decltype. 我的以下代码可以编译,但是不使用decltype我不知道如何编写。 I have written my failed attempts in commented lines below the line which uses decltype. 我在使用decltype的行下面的注释行中写了失败的尝试。

#include <iostream>
#include <iterator>
#include <vector>

using namespace std;

template<class Out>
class Fill{
public:
  Fill(){}
  void fill(Out x){
    for(int i = 0; i != 10; i++)*x++ = i;
  }
};

int main(){
  vector<int> v;

  Fill<decltype(back_inserter(v))> f; //works

  //does not work
  //Fill<vector<int>::iterator> g;

  //does not work
  //Fill<back_insert_iterator<vector<int>> h;


  f.fill(back_inserter(v));
  copy(v.begin(),v.end(),ostream_iterator<int>(cout," "));
}

Thanks 谢谢

suresh 苏雷什

The type will be back_insert_iterater<vector<int> > . 类型将为back_insert_iterater<vector<int> > Your 3rd example doesn't work because you need a whitespace between the ">>". 您的第三个示例不起作用,因为在“ >>”之间需要一个空格。 See http://www.cplusplus.com/reference/std/iterator/back_insert_iterator/ , it simply holds a pointer to the container type and redefines operator= to be container.push_back. 参见http://www.cplusplus.com/reference/std/iterator/back_insert_iterator/ ,它只是持有一个指向容器类型的指针,并将operator =重新定义为container.push_back。 I believe this is present so that std containers can work with std algorithms. 我相信这是存在的,以便std容器可以与std算法一起使用。 But, since you have control the definition to Fill you could simply allow the Fill class to hold a container pointer and call push_back directly against the container. 但是,由于您已经控制了Fill的定义,因此您可以简单地允许Fill类持有一个容器指针,并直接针对该容器调用push_back。

vector<int> ints;
typedef back_insert_iterator<vector<int>> InserterType; // This is what you need.
Fill<InserterType> f;
f.fill(back_inserter(ints));
copy(ints.begin(), ints.end(), ostream_iterator<int>(std::cout, "\n"));

如果您使用的是c ++ 0x,答案是:'auto':D

I figured out that the mistake in my original post was that I missed the 3rd right angled bracket in the definition of h . 我发现原始帖子中的错误是我错过了h定义中的第三个直角括号。 It should be corrected as 应该更正为

Fill<back_insert_iterator<vector<int>>> h;

Now the code would compile and work as intended. 现在,代码将按预期进行编译和工作。

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

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