c++unique用法
C++STL库中的unique函数是用来去除序列中连续的重复元素,并返回去重后序列的新结尾。其函数原型如下:
template<class ForwardIt>
ForwardIt unique(ForwardIt first, ForwardIt last);
其中,first和last表示序列的起始和结束迭代器。
unique函数会将连续的重复元素挪到序列的尾部,并返回一个新的迭代器,该迭代器指向去重后的序列的新结尾。例如:
std::vector<int> v = {1, 1, 2, 2, 3, 3, 4, 4, 4};
auto it = std::unique(v.begin(), v.end());
字符串函数去重 // 现在v中的元素为{1, 2, 3, 4, 4, 4}
// it指向v中的第5个元素,即最后一个4的下一个位置
注意,unique函数只能去除相邻的重复元素,如果要去除所有重复元素,需要先对序列进行排序。例如:
std::vector<int> v = {4, 2, 3, 1, 4, 2, 4, 3, 1};
std::sort(v.begin(), v.end());
auto it = std::unique(v.begin(), v.end());
// 现在v中的元素为{1, 2, 3, 4}
// it指向v中的第4个元素,即最后一个4的下一个位置
unique函数也可以接受一个函数对象作为参数,用来自定义去重规则。例如,去除字符串序列中的重复元素可以使用以下代码:
std::vector<std::string> v = {'hello', 'world', 'hello', 'cpp', 'world'};
auto it = std::unique(v.begin(), v.end(), [](const std::string& a, const std::string& b) {
return a==b;
});
// 现在v中的元素为{'hello', 'world', 'cpp', 'world'}
// it指向v中的第3个元素,即'cpp'的下一个位置
以上就是C++ STL库中unique函数的详细使用方法。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论