C++ trying to swap values in a vector

后端 未结 4 1583
礼貌的吻别
礼貌的吻别 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:37

    There is a std::swap in <algorithm>

    0 讨论(0)
  • 2020-12-01 04:46

    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
    
    0 讨论(0)
  • 2020-12-01 04:54

    after passing the vector by reference

    swap(vector[position],vector[otherPosition]);
    

    will produce the expected result.

    0 讨论(0)
  • 2020-12-01 04:57

    Both proposed possibilities (std::swap and std::iter_swap) work, they just have a slightly different syntax. Let's swap a vector's first and second element, v[0] and v[1].

    We can swap based on the objects contents:

    std::swap(v[0],v[1]);
    

    Or swap based on the underlying iterator:

    std::iter_swap(v.begin(),v.begin()+1);
    

    Try it:

    int main() {
      int arr[] = {1,2,3,4,5,6,7,8,9};
      std::vector<int> * v = new std::vector<int>(arr, arr + sizeof(arr) / sizeof(arr[0]));
      // put one of the above swap lines here
      // ..
      for (std::vector<int>::iterator i=v->begin(); i!=v->end(); i++)
        std::cout << *i << " ";
      std::cout << std::endl;
    }
    

    Both times you get the first two elements swapped:

    2 1 3 4 5 6 7 8 9
    
    0 讨论(0)
提交回复
热议问题