Re: erase function in vector
On Sep 24, 5:27 am, Jun <junh...@gmail.com> wrote:
Hello,
I've a vector of integer 4 4 4 5 9
suppose I deleted 5, i got 4 4 4 9
and sort by decreasing number ordering : 9 4 4 4
but when i output *(vector.end()), it aways show 9
But vector.end() still works when during loop.
vector<int> v;
// initialize
vector<int>::iterator ir = v.begin();
while(ir != v.end()){
if(*ir == 5)
ir = v.erase(ir);
else
++ir;
}
cout << *v.end() << endl;
sort(v.begin(),v.end(), sortbySize);
cout << *v.end() << endl;
std::copy(v.begin(),v.end(), ostream_iterator<int>(cout, "\t"));
The iterator and the value which it's represented is not much ... ?
very strange ...
{ Please remove extraneous material, such as the clc++m banner,
from your quoting. -mod }
Hi,
I tested and found things are working fine. Which compiler did you
use? It seems that you are directly accessing v.end(), which is a
pointer to a region one away from last element. Please check the code
below. In case of no obvious bugs, provide the source code as it is.
std::vector<int> v(5);
v[0] = 4; v[1] = 4; v[2] = 4; v[3] = 5; v[4] = 9;
// initialize
std::vector<int>::iterator ir = v.begin();
while(ir != v.end())
{
if(*ir == 5)
ir = v.erase(ir);
else
{
std::cout << std::endl << *ir << std::endl;
++ir;
}
}
std::cout << *(--v.end()) << std::endl;
std::sort(v.begin(),v.end(), std::greater<int>());
std::cout << *(--v.end()) << std::endl;
std::copy(v.begin(),v.end(), std::ostream_iterator<int>(std::cout,
"\t"));
Regards,
Karthik.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]