c++ - 将列表插入列表向量 std::vector>
问题描述
我正在尝试使用迭代器插入(const_iterator position,InputIterator first,InputIterator last)将列表插入到列表向量中;
std::vector<std::list<unsigned>> output;
std::list<unsigned> originalFile = {2, 6, 3, 56, 4, 29, 9, 43, 8, 12,
76, 45, 90, 124, 23, 11, 56, 26, 80, 13};
auto iter = originalFile.begin(); //it has 20 positive int inside
std::list<unsigned> sortedList;
unsigned int i = 0;
unsigned int v = 0;
unsigned int numFiles = originalFile.size() / m;
unsigned int index = originalFile.size() % m;
if(index != 0){
numFiles += 1;
}
while(numFiles != v)
{
while(i != m)
{
sortedList.push_back(*iter);
i++;
iter++;
}
sortedList.sort();
// the error point to this line with the insert function
output.insert(output.end(),sortedList.begin(),sortedList.end());
v++;
i = 0;
sortedList.clear();
}
并且在使用 ./build 构建文件时出现以下两个错误
/usr/lib/llvm-11/bin/../include/c++/v1/algorithm:1701:19:error: no viable overloaded '=' *__result = *__first;
/usr/lib/llvm-11/bin/../include/c++/v1/algorithm:1710:12: error: no matching function for call to '__copy_constexpr' return __copy_constexpr(__first, __last, __result);
我也尝试改用 push_back,但是Segmentation fault
当我使用 ./run gtest 运行 gtest 时出现错误。它构建成功,但测试失败。
for(auto iterList = sortedList.begin(); iterList != sortedList.end(); iterList++)
{
output[v].push_back(*iterList);
}
另外,我尝试使用上面的代码output.at(v).puch_back(*iterList)
,但构建成功,它给了我错误C++ exception with description "vector" thrown in the test body.
解决方案
output.insert(output.end(), sortedList.begin(), sortedList.end());
这会将一系列元素(在迭代器之间)附加到向量的末尾。如果你有 - 例如 -std::vector<unsigned> output
和std::list<unsigned> sortedList
. 但是,您希望将整个列表插入到列表向量中。该列表将是一个元素
output.insert(output.end(), sortedList); // <-- copy/move insertion
这看起来有点尴尬。更好的使用
output.push_back(sortedList);
推荐阅读
- python - Tkinter 按钮不出现
- python - 如何在 Seaborn 热图中添加垂直线
- excel - 如何在 Apache POI 中模拟 Excel 的“填写”?
- c# - Automapper:如何反转空替换?
- javascript - Bitboard Javascript - 如何识别确切的棋子/位置正在攻击国王
- python - AttributeError:对象没有属性 Python 错误
- r - R中两个以上二元(分类)变量的相关性分析
- python - setuptools_scm:如何在 gitflow 中合并时将“-alpha”附加到包版本?
- web-applications - 是否可以从软件文档构建 Web 应用程序,更具体地说是基于 Web 的编辑器
- javascript - 在另一个脚本中创建一个请求对象而不导入