首页 > 解决方案 > 将列表插入列表向量 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 构建文件时出现以下两个错误

  1. /usr/lib/llvm-11/bin/../include/c++/v1/algorithm:1701:19:error: no viable overloaded '=' *__result = *__first;
  2. /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.

标签: c++

解决方案


output.insert(output.end(), sortedList.begin(), sortedList.end());

这会将一系列元素(在迭代器之间)附加到向量的末尾。如果你有 - 例如 -std::vector<unsigned> outputstd::list<unsigned> sortedList. 但是,您希望将整个列表插入到列表向量。该列表将是一个元素

output.insert(output.end(), sortedList); // <-- copy/move insertion

这看起来有点尴尬。更好的使用

output.push_back(sortedList);

推荐阅读