我有totalSortedRuns
个文件。我想在向量中打开它们。我为此使用了两种方法:
vector<ifstream> files;
const char * fileName;
for(int i = 1; i<=totalSortedRuns; i++){
fileName = (inputFileName + to_string(i)).c_str();
files[i].open(fileName);
}
尝试过此方法,因为下面的方法不起作用。这在运行时会产生分段错误,显然是因为我的向量files
为空,并且正在将值分配给它的0-th
元素。为了解决这个问题,我尝试分配files.push_back(NULL)
,但它给了我错误
error: no matching function for call to ‘std::vector<std::basic_ifstream<char> >::push_back(NULL)’
方法2:
vector<ifstream> files;
ifstream file;
const char * fileName;
for(int i = 1; i<=totalSortedRuns; i++){
fileName = (inputFileName + to_string(i)).c_str();
file.open(fileName);
files.push_back(file); // line no 178 in code
}
但是这给了我错误:
In file included from /usr/include/x86_64-linux-gnu/c++/8/bits/c++allocator.h:33,
from /usr/include/c++/8/bits/allocator.h:46,
from /usr/include/c++/8/string:41,
from /usr/include/c++/8/bits/locale_classes.h:40,
from /usr/include/c++/8/bits/ios_base.h:41,
from /usr/include/c++/8/ios:42,
from /usr/include/c++/8/ostream:38,
from /usr/include/c++/8/iostream:39,
from invertedIndex.cpp:1:
/usr/include/c++/8/ext/new_allocator.h: In instantiation of ‘void __gnu_cxx::new_allocator<_Tp>::construct(_Up*, _Args&& ...) [with _Up = std::basic_ifstream<char>; _Args = {const std::basic_ifstream<char, std::char_traits<char> >&}; _Tp = std::basic_ifstream<char>]’:
/usr/include/c++/8/bits/alloc_traits.h:475:4: required from ‘static void std::allocator_traits<std::allocator<_CharT> >::construct(std::allocator_traits<std::allocator<_CharT> >::allocator_type&, _Up*, _Args&& ...) [with _Up = std::basic_ifstream<char>; _Args = {const std::basic_ifstream<char, std::char_traits<char> >&}; _Tp = std::basic_ifstream<char>; std::allocator_traits<std::allocator<_CharT> >::allocator_type = std::allocator<std::basic_ifstream<char> >]’
/usr/include/c++/8/bits/stl_vector.h:1079:30: required from ‘void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = std::basic_ifstream<char>; _Alloc = std::allocator<std::basic_ifstream<char> >; std::vector<_Tp, _Alloc>::value_type = std::basic_ifstream<char>]’
invertedIndex.cpp:178:29: required from here
/usr/include/c++/8/ext/new_allocator.h:136:4: error: use of deleted function ‘std::basic_ifstream<_CharT, _Traits>::basic_ifstream(const std::basic_ifstream<_CharT, _Traits>&) [with _CharT = char; _Traits = std::char_traits<char>]’
{ ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/x86_64-linux-gnu/c++/8/bits/stdc++.h:70,
from invertedIndex.cpp:6:
/usr/include/c++/8/fstream:552:7: note: declared here
basic_ifstream(const basic_ifstream&) = delete;
^~~~~~~~~~~~~~
从[C0行开始,我了解到错误出在invertedIndex.cpp:178:29: required from here
中。我无法理解此错误的确切含义和原因。
有人可以告诉我该怎么做(读取矢量文件吗?谢谢...
错误消息是不言自明的。 files.push_back(file)
的副本构造函数已删除。通过将ifstream
推到矢量上,您已请求复制。这可以通过将文件移到矢量中来解决:ifstream
。