std::forward_list unique() 方法
- 自 C++20 起
- 自 C++11 起
// (1) Non const version only
size_type remove( const T& value );
// (2) Non const version only
template< class UnaryPredicate >
size_type remove_if( UnaryPredicate p );
// (1) Non const version only
void remove( const T& value );
// (2) Non const version only
template< class UnaryPredicate >
void remove_if( UnaryPredicate p );
从容器中移除所有连续的重复元素。
每组相等元素只保留第一个元素。
未定义行为
行为未定义
如果选择的比较器不比较等价性。参数
-
返回p
- 二元谓词true
表示元素应被视为相等。谓词函数的签名应等同于以下内容
bool cmp( const Type1& a, const Type2& b )
虽然签名不需要
const&
,但函数不得修改传递给它的对象,并且必须能够接受任何值类别的(可能为 const)Type1
和Type2
类型的值(因此,不允许使用Type1&
,除非对于Type1
移动等同于复制,否则也不允许使用Type1
(自 C++11 起))。Type1
和Type2
的类型必须使得forward_list<T, Allocator>::const_iterator
类型的对象可以被解引用,然后隐式转换为两者。
返回值
移除的元素数量。 (自 C++20 起)(无) (直到 C++20)
复杂度
如果容器非空,则进行正好 std::distance(begin(), end()) - 1
次元素比较。否则,不进行任何比较。
异常
(无)
备注
功能测试宏:__cpp_lib_list_remove_return_type
。
示例
Main.cpp
#include <iostream>
#include <forward_list>
auto print = [](auto remark, auto const& container) {
std::cout << remark;
for (auto const& val : container)
std::cout << ' ' << val;
std::cout << '\n';
};
int main()
{
std::forward_list<int> c = {1, 2, 2, 3, 3, 2, 1, 1, 2};
print("Before unique():", c);
const auto count1 = c.unique();
print("After unique(): ", c);
std::cout << count1 << " elements were removed\n";
c = {1, 2, 12, 23, 3, 2, 51, 1, 2, 2};
print("Before unique(pred):", c);
const auto count2 = c.unique([mod=10](int x, int y) {
return (x % mod) == (y % mod);
});
print("After unique(pred): ", c);
std::cout << count2 << " elements were removed\n";
}
输出
Before unique(): 1 2 2 3 3 2 1 1 2
After unique(): 1 2 3 2 1 2
3 elements were removed
Before unique(pred): 1 2 12 23 3 2 51 1 2 2
After unique(pred): 1 2 23 2 51 2
4 elements were removed