How to reverse the order of elements in vector using C++

2 Answers

0 votes
#include <iostream>
#include <vector>

using std::cout;
using std::endl;

template <typename T>
inline void print(const T& obj)
{
	for (auto element : obj) {
		cout << element << ' ';
	}
	cout << endl;
}

int main()
{
	std::vector<int> vec = { 0, 1, 2, 3, 4, 5, 6 };

	print(vec);

	std::reverse(vec.begin(), vec.end());

	print(vec);

	return 0;
}

/*
run:

0 1 2 3 4 5 6
6 5 4 3 2 1 0

*/

 



answered Feb 22, 2018 by avibootz
0 votes
#include <iostream>
#include <vector>

using std::cout;
using std::endl;

template <typename T>
inline void print(const T& obj)
{
	for (auto element : obj) {
		cout << element << ' ';
	}
	cout << endl;
}

int main()
{
	std::vector<int> vec = { 0, 1, 2, 3, 4, 5, 6 };
	std::vector<int>::size_type size = vec.size();

	print(vec);
	
	for (unsigned i = 0; i < size / 2; i++)
	{
		int tmp;

		tmp = vec[size - 1 - i];
		vec[size - 1 - i] = vec[i];
		vec[i] = tmp;
	}

	print(vec);

	return 0;
}

/*
run:

0 1 2 3 4 5 6
6 5 4 3 2 1 0

*/

 



answered Feb 22, 2018 by avibootz

Related questions

1 answer 192 views
2 answers 226 views
1 answer 205 views
3 answers 229 views
1 answer 155 views
1 answer 156 views
...