ページ 1 / 1
unique関数について
Posted: 2009年9月24日(木) 19:48
by dic
unique関数についてですが
以下のように実装するのですが、重複した要素が取り除かれません
どこが間違っているのでしょうか?
#pragma warning( disable: 4786 )
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
static vector<string> gvSrc;
void sub()
{
char *mes[/url] = { "this", "this", "this", "this" };
int i;
for( i=0; i<4; i++ )
gvSrc.push_back( mes );
unique( gvSrc.begin(), gvSrc.end() );
for( i=0; i<gvSrc.size(); i++ )
cout << gvSrc.at(i).c_str() << endl;
}
void main()
{
sub();
}
Re:unique関数について
Posted: 2009年9月24日(木) 20:09
by MNS
unique関数のような、削除関係のアルゴリズム関数は、
実際には値を削除せず、値を末尾へと移動させます。
よって、末尾には値が残ったままになるので、これを削除しなければいけません。
以下のようなコードになります。
#pragma warning( disable: 4786 )
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
static vector<string> gvSrc;
void sub()
{
char *mes[/url] = { "this", "this", "this", "this" };
int i;
for( i=0; i<4; i++ )
gvSrc.push_back( mes );
vector<string>::iterator it = unique( gvSrc.begin(), gvSrc.end() );
gvSrc.erase(it, gvSrc.end());
for( i=0; i<gvSrc.size(); i++ )
cout << gvSrc.at(i).c_str() << endl;
}
void main()
{
sub();
}
Re:unique関数について
Posted: 2009年9月24日(木) 20:24
by dic
>unique関数のような、削除関係のアルゴリズム関数は、
>実際には値を削除せず、値を末尾へと移動させます。
そのようですね
なんともややこしい説明だ・・・
MNSさんの回答を参考に改良し、解決しました
#pragma warning( disable: 4786 )
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
static vector<string> gvSrc;
void sub()
{
char *mes[/url] = { "this", "there", "this", "this", "there", "there" };
int i;
for( i=0; i<6; i++ )
gvSrc.push_back( mes );
vector<string>::iterator p, p_end;
sort( gvSrc.begin(), gvSrc.end() );
p_end = unique( gvSrc.begin(), gvSrc.end() );
// 改良前
cout << "改良前" << endl;
for( i=0; i<gvSrc.size(); i++ )
cout << gvSrc.at(i).c_str() << endl;
cout << "改良後" << endl;
// 改良後
cout << "gvSrc.size:" << gvSrc.size() << endl;
for( p=gvSrc.begin(); p!=p_end; p++ )
cout << *p << endl;
// MNSさんの回答を参考に
cout << "改良後 その2" << endl;
gvSrc.erase( p_end, gvSrc.end() );
cout << "gvSrc.size:" << gvSrc.size() << endl;
for( i=0; i<gvSrc.size(); i++ )
cout << gvSrc.at(i).c_str() << endl;
}
void main()
{
sub();
}