c++代码无法编译并出现奇怪的错误

标签 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: In instantiation of ‘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: required from ‘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: required from ‘void std::__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:4836:18: required from ‘void std::sort(_RAIter, _RAIter) [with _RAIter = __gnu_cxx::__normal_iterator >]’ a.cpp:16:31: required from here /usr/include/c++/7/bits/stl_algo.h:1852:17: error: assignment of read-only location ‘__first.__gnu_cxx::__normal_iterator >::operator*()’ *__first = _GLIBCXX_MOVE(__val);

最佳答案

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

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

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

关于c++代码无法编译并出现奇怪的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56476524/

相关文章:

c++ - 在堆上创建多维数组

c++ - Another C++ was not declared in this scope 错误

c++ - 将 std::sort 替换为 boost::sort

c++ - 在 lambda 表达式中调用方法

c++ - 如何根据模板类的基类专门化成员函数

c++ - 如何优化获取数组中的最大值?

c++ -/proc/fd 文件描述符显示什么?

c++ - 如何删除密码屏蔽c++中的字符

c++ - 无法访问对象指针,即使它没有被删除

c++ - 动态规划问题 - 最小成本路径