C++ trying to swap values in a vector(C++ 试图交换向量中的值)
问题描述
这是我的交换函数:
template <typename t>
void swap (t& x, t& y)
{
t temp = x;
x = y;
y = temp;
return;
}
这是我的函数(在旁注中 v 存储字符串)调用交换值,但是每当我尝试使用向量中的值调用时,我都会收到错误消息.我不确定我做错了什么.
And this is my function (on a side note v stores strings) call to swap values but whenever I try to call using values in a vector I get an error. I'm not sure what I'm doing wrong.
swap(v[position], v[nextposition]); //creates errors
推荐答案
我认为您正在寻找的是 iter_swap
也可以在 中找到.
您需要做的就是传递两个迭代器,每个迭代器都指向您要交换的元素之一.
因为你有两个元素的位置,你可以做这样的事情:
I think what you are looking for is iter_swap
which you can find also in <algorithm>
.
all you need to do is just pass two iterators each pointing at one of the elements you want to exchange.
since you have the position of the two elements, you can do something like this:
// assuming your vector is called v
iter_swap(v.begin() + position, v.begin() + next_position);
// position, next_position are the indices of the elements you want to swap
这篇关于C++ 试图交换向量中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 试图交换向量中的值
基础教程推荐
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- Windows Media Foundation 录制音频 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01