读书人

求问C++ unique()函数使用有关问题

发布时间: 2012-04-11 17:42:33 作者: rapoo

求问C++ unique()函数使用问题!
小弟最后在看C++ primer,在运用unique()函数时,遇到了一个问题。程序如下,希望大牛解答啊!
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
vector<string> vec_str;
vec_str.push_back("the");
vec_str.push_back("quick");
vec_str.push_back("red");
vec_str.push_back("fox");
vec_str.push_back("jumps");
vec_str.push_back("over");
vec_str.push_back("the");
vec_str.push_back("slow");
vec_str.push_back("red");
vec_str.push_back("turtle");
vector<string>::iterator iter1 = vec_str.begin(), iter2 = vec_str.end();
while(iter1 != iter2)
{
cout<<*iter1++<<" ";
}
cout<<"\n\n";
sort( vec_str.begin(), vec_str.end());

iter1 = vec_str.begin(), iter2 = vec_str.end();
while(iter1 != iter2)
{
cout<<*iter1++<<" ";
}
cout<<"\n\n";
unique(vec_str.begin(), vec_str.end());

iter1 = vec_str.begin(), iter2 = vec_str.end();
int i=0;
while(iter1 != iter2)
{
cout<<*iter1++<<" ";
i++;
}
cout<<"\n\n"<<i<<endl;
cin.get();
}
调试这个程序出了一个问题!
调用sort()函数之后,vec_str中存储 fox jumps over quick red red slow the the turtle
调用unique()函数之后,vec_str中存储 fox jumps over quick red slow the turtle the turtle,为啥?(按书上讲应该输出 fox jumps over quick red slow the turtle the red 吧);


还有一个问题是最后一个while()循环中,迭代器用的有问题吗?为啥vec_str输出前9个字符串,最后一个总是一个空字符串?到底是出了什么问题啊?
小弟初学C++,不知道怎么解决这个问题,望大牛帮忙啊,非常感谢!

[解决办法]
楼主还是找本《effective stl》看看吧,关于unique。
另外,楼主听说排序的“稳定性”问题没有?这和你的最后数据是啥有关。
[解决办法]
也可以参考http://www.cplusplus.com/reference/algorithm/unique/

读书人网 >C++

热点推荐