C++ trying to swap values in a vector

后端 未结 4 1606
礼貌的吻别
礼貌的吻别 2020-12-01 04:18

This is my swap function:

template 
void swap (t& x, t& y)
{
    t temp = x;
    x = y;
    y = temp;
    return;
}
4条回答
  •  再見小時候
    2020-12-01 04:46

    I think what you are looking for is iter_swap which you can find also in .
    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
    

提交回复
热议问题