Reversing vector content

Hi I am trying to reverse the contents of a vector, and at run time the programme does not like the fact that I am calling .size() inside of .at(). Here is my code.

1
2
3
4
5
6
7
8
9
10
11
12
13

	std::vector<char> chr;
	for (unsigned int i = 0;i<data.size();i++)
	{
		chr.push_back(data.at(i));
	}

	std::vector<char> swap;
	for (unsigned int i = 0; i<chr.size(); i++)
	{
		swap.at(i)=chr.at(chr.size()-i);
		std::cout << swap.at(i);
	}


It does not like line 11. From the error window that appears it seems to be about memory "std::out_of_range at memory location....". Thanks.
What's wrong with std::reverse(chr.begin(), chr.end()); ?
Didn't know that existed. Thanks!
The runtime error results from two coding errors.
 
    std::vector<char> swap;
that is an empty vector, you need to allocate some elements:
 
    std::vector<char> swap(chr.size());


and this expression, when i==0, accesses the element after the last one:
chr.at(chr.size()-i)
It should be chr.at(chr.size()-i-1)

Topic archived. No new replies allowed.