C ++代码无法编译并产生奇怪的错误

时间:2019-06-06 11:20:36

标签: c++ c++11 c++14

这段c ++代码无法编译。有人知道为什么吗?

#include <functional>
#include <algorithm>
#include <vector>
#include <iostream>

int main(int a, char** v) {

        std::vector<uint32_t> v1 {1,2,3,4};
        std::vector<uint32_t> v2 {0};
        std::vector<uint32_t> v3 {5,4,3,11};
        std::vector<uint32_t> v4 {10,11,2};


        auto vector_is_subset = [] (const std::vector<uint32_t> a, const std::vector<uint32_t> b) -> bool {

                std::sort(a.begin(), a.end());
                std::sort(b.begin(), b.end());
                return std::includes(a.begin(), a.end(), b.begin(), b.end());
        };


        std::vector<uint32_t> f {};

        if (v1.empty() || v2.empty() || v3.empty() || v4.empty() ){
                std::cout << "a vector is empty" << std::endl;
        }


        return 0;
}

我得到以下输出

g ++ a.cpp -std = c ++ 14

在/ usr / include / c ++ / 7 / algorithm:62:0包含的文件中,                  来自a.cpp:2:

  

/ usr / include / c ++ / 7 / bits / stl_algo.h:实例化为“ void   std :: __ insertion_sort(_RandomAccessIterator,_RandomAccessIterator,   _Compare)[with _RandomAccessIterator = __gnu_cxx :: __ normal_iterator>; _Compare = __gnu_cxx :: __ ops :: __ Iter_less_iter]’:   /usr/include/c++/7/bits/stl_algo.h:1885:25:从'void必需   std :: __ final_insertion_sort(_RandomAccessIterator,   _RandomAccessIterator,_Compare)[with _RandomAccessIterator = __gnu_cxx :: __ normal_iterator>; _Compare = __gnu_cxx :: __ ops :: __ Iter_less_iter]’   /usr/include/c++/7/bits/stl_algo.h:1971:31:从'void必需   std :: __ sort(_RandomAccessIterator,_RandomAccessIterator,_Compare)   [使用_RandomAccessIterator = __gnu_cxx :: __ normal_iterator>; _比较=   __gnu_cxx :: __ ops :: _ Iter_less_iter]” /usr/include/c++/7/bits/stl_algo.h:4836:18:“void”中必填   std :: sort(_RAIter,_RAIter)[with _RAIter =   __gnu_cxx :: __ normal_iterator>]’a.cpp:16:31:从此处开始   /usr/include/c++/7/bits/stl_algo.h:1852:17:错误:分配   只读位置“ __first .__ gnu_cxx :: __ normal_iterator> :: operator *()”           * __ first = _GLIBCXX_MOVE(__ val);

1 个答案:

答案 0 :(得分:8)

std::sort修改了容器以使其排序,但是您将lambda的参数声明为const

auto vector_is_subset = [] (const std::vector<uint32_t> a, const std::vector<uint32_t> b) -> bool
                         // ^^^^                           ^^^^^

删除它们,它应该可以正常编译。