我有一个程序,我正在Windows上编写,我使用std :: vector的sort函数。它运行正常,但是当我在Linux上编译时,我收到一条错误消息:
‘sort’未在此声明……
没有功能 sort 在 std::vector 在任何一个平台上 ,所以我认为你正在使用 std::sort 迭代器范围从 std::vector 。
sort
std::vector
std::sort
这很好,也很正确。
错误消息表明两件事:
你在写 sort 不是 std::sort 。只要你写了,这将有效 using namespace std 虽然使用完全限定名称更好。继续。
using namespace std
你没写 #include <algorithm> 而是依赖于“传递包含”,即假设某些其他标题本身包括 <algorithm> ,情况可能就是这样 偶然 使用Visual Studio实现,但不使用libstdc ++或libc ++。
#include <algorithm>
<algorithm>
您应该始终包含适当的标准标头以保证可移植性。不要吝啬只是因为你的程序似乎在某些特定系统上没有它们的情况下工作。
这样做,我打赌你的问题会消失。
一般而言,除非标准合规性和/或工具链错误出现问题, 标准功能在操作系统中是相同的 。这就是为什么他们是标准的。
#include <vector> #include <algorithm> #include <iostream> int main() { std::vector<int> v{5,3,4,1,2}; std::sort(v.begin(), v.end()); for (const auto& el : v) std::cout << el << ' '; std::cout << '\n'; } // Output: 1 2 3 4 5