You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 22:36:24