首页 > 解决方案 > 如何在 C++ 中的整数类型向量中交换索引 2 和索引 3 处的值?

问题描述

问题:您必须在数组的第二个和第三个索引之间交换值。该数组是一个由 10 个元素组成的向量数组。

假设是;

std::vector<int> arr1 = { 33,12,11,13,54,65,23,67,22,10 };

最后结果:

交换前:

33 12 11 13 54 65 23 67 22 10

交换后:

33 12 13 11 54 65 23 67 22 10

附加信息:

  1. 任何围绕解决方案的逻辑概念都是允许的。
  2. 除了整数类型之外,数组应该能够采用其他数据类型。

标签: c++

解决方案


版本 1:使用std::swap

#include <iostream>
#include <algorithm>
#include <vector>
int main()
{
   std::vector<int> vec= { 33,12,11,13,54,65,23,67,22,10};
   std::swap(vec[2], vec[3]);
   
   for(const int &elem: vec)
   {
       std::cout<<elem<<std::endl;
   }
    return 0;
}

版本 2:手动使用temp变量

#include <iostream>
#include <vector>
//define a function template that takes the first argument as a vector of arbitrary type and second argument as first index to swap and the third argument as the second index to swap
template<typename T> 
void mySwap(std::vector<T>&vec, std::size_t indexOne, std::size_t indexTwo )
{
    
    T temp = vec.at(indexOne);
    vec.at(indexOne) = vec.at(indexTwo);
    vec.at(indexTwo) = temp;
}
int main()
{
    
   std::vector<int> vec= { 33,12,11,13,54,65,23,67,22,10};
   mySwap(vec, 2,3);
   
   for(const int &elem: vec)
   {
       std::cout<<elem<<std::endl;
   }
    return 0;
}

给出第二个版本只是为了说明如何实现与std::swap.


推荐阅读