C++ 试图交换向量中的值

2021-12-21 00:00:00 swap 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

相关文章