C++vector遍历一个容器,排序后删除重复项 vector iterator not dereferencable
vector<int>::iteratorit;//vector<int>::iteratortmp=y.begin();sort(y.begin(),y.end());...
vector<int>::iterator it;
//vector<int>::iterator tmp=y.begin();
sort(y.begin(),y.end());
for (it=y.begin();it!=y.end();)
{
it++;
while (*(it-1)==*it)
{
it=y.erase(it);
//it-1;
}
}
遍历一个容器,排序后删除重复项 展开
//vector<int>::iterator tmp=y.begin();
sort(y.begin(),y.end());
for (it=y.begin();it!=y.end();)
{
it++;
while (*(it-1)==*it)
{
it=y.erase(it);
//it-1;
}
}
遍历一个容器,排序后删除重复项 展开
展开全部
为何不用 unique?
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector< int > v;
for( int i = 0; i < 3; i++ )
{
for( int j = 0; j < 5; j++ )
{
v.push_back( j );
}
}
std::sort( v.begin(), v.end() );
v.erase( std::unique( v.begin(), v.end() ), v.end() );
for( size_t i = 0; i < v.size(); i++ )
std::cout << v[i] << std::endl;
return 0;
}
如果你一定要用iterator的话
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector< int > v;
for( int i = 0; i < 3; i++ )
{
for( int j = 0; j < 5; j++ )
{
v.push_back( j );
}
}
std::sort( v.begin(), v.end() );
if(v.size() <= 1)
return 0;
std::vector< int >::iterator it;
int last = v[0];
for( it = v.begin()+1; it != v.end(); )
{
if( (*it) == last )
it = v.erase( it );
else
{
++it;
last = *it;
}
}
for( size_t i = 0; i < v.size(); i++ )
std::cout << v[i] << std::endl;
return 0;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询