How to Use the Swap Function?

I tried to do an excercise from Stroupstrup's book. The reader is asked to reverse the
order of elements in a vector so that if originally vector[0] = 1, vector [1] = 2, and
vector[2] = 3, then new vector has newvec[0] = 3, newvec[1] = 2, and newvec[2] = 1.

Doing this through creating a new vector was straighforward. However, part b) of the
exercise requests the reader to reverse the elements WITHOUT creating a new vector.
I guess it means to reverse the elements of the original vector. Stroupstrup suggests
that the reader use the swap function to do this.

I researched the swap function and can't find any examples of it being used with ONE
vector. It is always used with two vectors as in
first.swap(second);.

I thought that it might be used for swapping elements as in
first[i].swap(first[first.size() - 1 -i]);.
But this gave me a memory allocation error.

This exercise is from the chapter (8) in which Stroustrup explains pass-by-reference.
I thought of trying to use pass-by-reference for swapping but I don't see how to formulate
that construction.

How does one use the swap function to reverse the order of elements in a vector without
using any other vectors?
Hint: you need to use iterators.

If you want to check your work, look at the documentation on this site for the std::reverse algorithm. It shows a simple implementation.
I think you need to use the std::swap() template function from <algorithm> rather than the std::vector's swap() function.

http://www.cplusplus.com/reference/algorithm/swap/
Forget about functions, think in the algorithm.
You guys were right, thank you. I was not using the correct form of the swap function. I should have used
swap(first,second);
When I did, the program compiled and ran correctly. Here is the code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include "../../std_lib_facilities.h"

void reverse(vector<int>v)
{
	for (int i = 0; i < v.size()/2; ++i) {
           swap(v[i], v[v.size()-1-i]);
	}

	for (int i = 0; i < v.size(); ++i) {
	   cout << i <<"  " << v[i] << endl;
	}
}

int main () 
{
	vector<int>cs;
	int c = 0;
    
	while (cin >> c) {
		if (c == -999) {
		    reverse(cs);
		    break;
		} else {
		cs.push_back(c);
		}
	}
	
    keep_window_open();
    return 0;
}

Topic archived. No new replies allowed.