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++ 试图交换向量中的值
基础教程推荐
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- c++ STL设置差异 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
