C ++试图在向量中交换值 [英] C++ trying to swap values in a vector

查看:156
本文介绍了C ++试图在向量中交换值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的交换函数:

template <typename t>
void swap (t& x, t& y)
{
    t temp = x;
    x = y;
    y = temp;
    return;
}

这是我的函数交换值,但每当我尝试调用使用矢量中的值我得到一个错误。我不确定我做错了什么。

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 您也可以在< algorithm> 中找到。

所有你需要做的只是传递两个迭代器,每个指向一个要交换的元素。

因为你有两个元素的位置,你可以这样做:

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() + nextPosition);
// position, nextPosition are the indices of the elements you want to swap

这篇关于C ++试图在向量中交换值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆