[英]Initializing a vector with stream iterators
我正在尝试使用迭代器初始化向量,并且出现编译器错误,基本上是说没有要调用的匹配函数。
该代码使用istream_iterator从文件中读取,并以输入前哨结束。 然后,我尝试使用这两个迭代器初始化向量。
#include "std_lib_facilities.h"
#include<iterator>
int main()
{
string from, to; // get source and target file names
cin >> from >> to;
ifstream is(from.c_str()); // open input stream
ofstream os(to.c_str()); // open output stream
istream_iterator<string> ii(is); // make input iterator for stream
istream_iterator<string> eos; // input sentinel
ostream_iterator<string> oo(os,"\n");
vector<string> words(ii, eos); // vector initialized from input
sort(words.begin(), words.end()); // sort the buffer
copy(words.begin(), words.end(), oo); // copy buffer to output
}
我知道我可以使用复制功能将输入流复制到向量中,但是我读到它也可以通过这种方式完成。 谁能解释为什么不编译? 谢谢。
编译器错误:
C:\Users\Alex\C++\stream_iterators.cpp|16|error: no matching function for call to `Vector<String>::Vector(std::istream_iterator<String, char, std::char_traits<char>, ptrdiff_t>&, std::istream_iterator<String, char, std::char_traits<char>, ptrdiff_t>&)'|
编辑:这不是标题问题。 Std_lib_facilities具有所有必需的标头。
vector<string> words(ii, eos);
是类似于
vector<string> words;
copy( ii, eos, back_inserter(words) );
vector
类具有以下构造函数:
// initialize with range [First, Last)
template<class InputIterator>
vector(
InputIterator First,
InputIterator Last
);
要进行示例编译,您需要包括以下内容:
#include <sstream>
#include <iostream>
#include <vector>
#include <fstream>
#include <algorithm> // for std::copy
由于您的标识符不完全合格,因此应添加以下内容:
using namespace std;
或完全限定所有STL标识符。
我想要改变
copy(words.begin(), words.end(), out)
至
copy(words.begin(), words.end(), oo)
请复制并粘贴编译器错误。 另外,您缺少许多标头,例如算法和向量。 您需要使用命名空间std声明或使用std ::来访问STL类。
提供更多信息后,我们将为您提供更多建议。
更新:为什么您的错误消息引用的是“向量”(大写),而不是向量(小写)?
图书标题存在某种合规性问题,因此我只包含了适当的标题就可以了。
std_lib_facilities.h中的Vector类定义了三个构造函数,但没有一个接受一对迭代器。 您可以继续将其添加到标题中:
template <class Iter>
Vector(Iter from, Iter to): std::vector<T>(from, to) {}
使用此标头时,您需要考虑到这是用于手持的。 实际std :: vector中的operator []不应进行范围检查。 (为什么不只是教导初学者使用vector :: at,直到他们意识到保持边界可能更好……?)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.