'['之前的预期表达式

expected expression before '['

本文关键字:表达式      更新时间:2023-10-16

我是一个编程新手。最近我尝试使用c++中的排序函数来跟踪索引

template <typename T>
std::vector<size_t> ordered(std::vector<T> const& values) {
std::vector<size_t> indices(values.size());
std::iota(begin(indices), end(indices), static_cast<size_t>(0));
std::sort(
    begin(indices), end(indices),
    [&](size_t a, size_t b) { return values[a] < values[b]; }
);
return indices;
}
在Xcode中,它被成功编译而没有任何警告。而在g++中,它显示以下错误消息:
error: expected expression
          [&](size_t a, size_t b) { return values[a] < values[b];}
          ^

它暗示了什么?谢谢!

beginend属于std命名空间。您需要限定它们:

std::sort(
    std::begin(indices), std::end(indices),
    [&](size_t a, size_t b) { return values[a] < values[b]; }
);

lambda也是c++ 11的一个特性,所以你需要用-std=c++11编译才能使用它们。