'[' 之前的预期表达式

expected expression before '['

我是编程新手。最近我尝试使用 c++ sort keeping track of indices

中的排序功能
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]; }
);

另外 lambdas 是 C++11 的特性,因此您需要使用 -std=c++11 进行编译才能使用它们。