【问题标题】:Swap two elements in static array using STL [closed]使用 STL 交换静态数组中的两个元素 [关闭]
【发布时间】:2013-12-09 20:30:04
【问题描述】:

假设我有一个数组,int array[3] = {1,2,3};,我想交换第一个和最后一个元素,这样我就有了array = {3,2,1};,我怎样才能使用 STL 做到这一点?

【问题讨论】:

    标签: c++ arrays stl


    【解决方案1】:

    您可以使用std::swapstd::iter_swap

        std::swap(array[0], array[2]);
        std::iter_swap(array, array+2);
    

    【讨论】:

      【解决方案2】:

      对于不依赖数组长度为3的解决方案,可以使用std::beginstd::end找到array的开头和结尾,然后std::iter_swap他们

      std::iter_swap(std::begin(array), std::end(array)-1);
      

      注意-1 因为可迭代对象的end 指的是结束后的一个元素。您需要 #include <iterator>#include <algorithm> 才能正常工作。

      如果你想更灵活,你可以创建一个模板函数

      template <typename T>
      void swap_first_and_last(T& seq) {
          std::iter_swap(std::begin(seq), std::end(seq)-1);
      }
      

      然后可以用静态数组(或其他容器)调用它

          swap_first_and_last(array);
      

      另一个注意事项:使用初始化列表,您不需要为数组提供大小。编译器会根据你提供的元素数量计算出一个:

      int array[] = {1,2,3};  //empty []
      

      【讨论】:

        猜你喜欢
        • 2012-10-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-30
        • 2016-05-15
        • 2023-03-24
        相关资源
        最近更新 更多