c++ - 如何在 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:使用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
.
推荐阅读
- c# - 如何使用 c# Console.WriteLine() 显示空间代码(例如,三角形项目符号:\u2023)n 次
- php - 如果服务器是 https(SSL 活动),则 TCPDF 不会加载 http 图像链接
- jquery - array.push 在 ajax 和 for 循环中不起作用
- ios - 几天前如何在 UNNotificationCenter 中设置警报?
- ffmpeg - 使用 ffmpeg 解码部分视频时,有没有办法消除寻道时间?
- php - 我们如何使用 foreach 循环获取下一个元素键的键
- java - 为什么 Gradle Wrapper JAR 校验和在由 Ubuntu 包中的 gradle 二进制文件生成时不匹配
- python - Python:在对数组进行排序的示例中理解递归
- html - Grafana for user authenticated data visualization
- dropzone.js - limit dropzone to single file