vector

can anyone help me to write a swap function to swap 2 elements in the vector?
thanks
C++ already provides a "universal" swap function.
So by writing a swap() function yourself, you are reinventing the wheel.

http://www.cplusplus.com/reference/utility/swap/
sorry, I don't mean to swap 2 vectors and I already tried the swap function in algorithm library and that didn't work either
this is what I been working on
I have a class that using the vector under the hood so I have a whole bunch of data in the vector. I am trying to swap 2 elements in the array it doesn't work and I am running out of time. thanks
The std::swap() function can be used to swap two elements.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <utility>
#include <vector>

int main()
{
    std::vector<int> v1 {1, 1, 1, 1};
    std::vector<int> v2 {2, 2, 2, 2};

    std::swap(v1[1], v2[1]);
    std::swap(v1[3], v2[3]);
    std::cout << "v1 contents: ";

    for (int i: v1)
        std::cout << i << ' ';

    std::cout << "\nv2 contents: ";

    for (int i: v2)
        std::cout << i << ' ';

    std::cout << std::endl;
}
v1 contents: 1 2 1 2 
v2 contents: 2 1 2 1 
Topic archived. No new replies allowed.