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?

Recommended Answers

All 3 Replies

There is another swap function/. It swaps the two variables. So now its up to you to use that to swap variables around in your vector.

You have been looking at the wrong swap function. He means the swap function in the <algorithm> header. see this page on it.

If you don't understand the template syntax, just assume it works for any type "T", and leave it at that for now. You would use it as, say:

#include <algorithm>

..
    swap(vector[0],vector[2]); //leave vector[1] as before.
..

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.

#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;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.