怎样使用unique函数

发布网友

我来回答

2个回答

热心网友

需求
头文件: <algorithm>

示例

// alg_unique.cpp
// compile with: /EHsc
#include <vector>
#include <algorithm>
#include <functional>
#include <iostream>
#include <ostream>

using namespace std;

// Return whether molus of elem1 is equal to molus of elem2
bool mod_equal ( int elem1, int elem2 )
{
if ( elem1 < 0 )
elem1 = - elem1;
if ( elem2 < 0 )
elem2 = - elem2;
return elem1 == elem2;
};

int main( )
{
vector <int> v1;
vector <int>::iterator v1_Iter1, v1_Iter2, v1_Iter3,
v1_NewEnd1, v1_NewEnd2, v1_NewEnd3;

int i;
for ( i = 0 ; i <= 3 ; i++ )
{
v1.push_back( 5 );
v1.push_back( -5 );
}

int ii;
for ( ii = 0 ; ii <= 3 ; ii++ )
{
v1.push_back( 4 );
}
v1.push_back( 7 );

cout << "Vector v1 is ( " ;
for ( v1_Iter1 = v1.begin( ) ; v1_Iter1 != v1.end( ) ; v1_Iter1++ )
cout << *v1_Iter1 << " ";
cout << ")." << endl;

// Remove consecutive plicates
v1_NewEnd1 = unique ( v1.begin ( ) , v1.end ( ) );

cout << "Removing adjacent plicates from vector v1 gives\n ( " ;
for ( v1_Iter1 = v1.begin( ) ; v1_Iter1 != v1_NewEnd1 ; v1_Iter1++ )
cout << *v1_Iter1 << " ";
cout << ")." << endl;

// Remove consecutive plicates under the binary prediate mod_equals
v1_NewEnd2 = unique ( v1.begin ( ) , v1_NewEnd1 , mod_equal );

cout << "Removing adjacent plicates from vector v1 under the\n "
<< " binary predicate mod_equal gives\n ( " ;
for ( v1_Iter2 = v1.begin( ) ; v1_Iter2 != v1_NewEnd2 ; v1_Iter2++ )
cout << *v1_Iter2 << " ";
cout << ")." << endl;

// Remove elements if preceded by an element that was greater
v1_NewEnd3 = unique ( v1.begin ( ) , v1_NewEnd2, greater<int>( ) );

cout << "Removing adjacent elements satisfying the binary\n "
<< " predicate mod_equal from vector v1 gives ( " ;
for ( v1_Iter3 = v1.begin( ) ; v1_Iter3 != v1_NewEnd3 ; v1_Iter3++ )
cout << *v1_Iter3 << " ";
cout << ")." << endl;
}

参考资料: ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.VisualStudio.v80.chs/dv_vcstdlib/html/a9615038-2b77-43bf-876b-9f79be88eff0.htm

热心网友

我也是初学者

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com