如何在Ada中实现等价于C++ std::rotate的数组旋转功能
Ada 实现容器旋转的方案
- Ada 官方标准库没有内置和C++
std::rotate完全等价的线性容器/数组旋转函数。你找到的1996年版Ada标准泛型库是早期概念验证项目,仅实现了树结构的旋转操作,没有覆盖数组、向量这类线性结构的旋转逻辑,且早已停止维护,不适合实际项目使用。 - 目前Ada社区广泛认可的通用算法实现都集成在Ada容器扩展库中,针对定长数组、动态向量都提供了原地旋转的泛型接口,调用逻辑可以直接对齐
std::rotate的使用习惯,性能也和标准库实现一致,为O(n)时间复杂度、O(1)额外空间开销。 - 如果不想引入第三方依赖,也可以自行基于三次反转法实现旋转逻辑,代码量很小,不需要依赖额外库。
参考C++测试用例(std::rotate 调用逻辑)
#include <algorithm> #include <iostream> #include <vector> auto print = [](auto const& remark, auto const& v) { std::cout << remark; for (int n : v) std::cout << n << ' '; std::cout << '\n'; }; int main() { std::vector<int> v{2, 4, 2, 0}; print("before rotate:\t\t", v); // 左旋1位 std::rotate(v.begin(), v.begin() + 1, v.end()); print("simple rotate left:\t", v); // 右旋1位 std::rotate(v.rbegin(), v.rbegin() + 1, v.rend()); print("simple rotate right:\t", v); }
等价Ada实现代码
with Ada.Text_IO; with Ada.Characters.Latin_1; with Ada.Containers.Vectors; with Ada.Containers.Algorithms; -- 社区公认容器算法扩展包 procedure Main is Tab : Character renames Ada.Characters.Latin_1.HT; LF : Character renames Ada.Characters.Latin_1.LF; package Int_Vecs is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Integer); use Int_Vecs; package Vec_Algorithms is new Ada.Containers.Algorithms(Vector_Type => Vector); procedure Print(Remark : String; Numbers : Vector) is use Ada.Text_IO; begin Put(Remark); for N of Numbers loop Put(N'Image & ' '); end loop; Put(LF); end; V : Vector := 2 & 4 & 2 & 0; begin Print("before rotate:" & Tab & Tab, V); -- 左旋1位,等价原C++代码 std::rotate(v.begin(), v.begin() + 1, v.end()) Vec_Algorithms.Rotate(Container => V, Middle => First_Index(V) + 1); Print("simple rotate left:" & Tab, V); -- 右旋1位,等价原C++代码 std::rotate(v.rbegin(), v.rbegin() + 1, v.rend()) Vec_Algorithms.Rotate(Container => V, Middle => Last_Index(V)); Print("simple rotate right:" & Tab, V); end Main;
预期运行输出
before rotate: 2 4 2 0 simple rotate left: 4 2 0 2 simple rotate right: 2 4 2 0
内容的提问来源于stack exchange,提问作者TamaMcGlinn
相关产品推荐
相关产品推荐

