网站开发创业计划书模板,长沙市网站推广电话,电商网站建设哪家好,成都关键词优化声明#xff1a;本文内容生成自ChatGPT#xff0c;目的是为方便大家了解学习作为引用到作者的其他文章中。 std::unique 是 C 标准库中的一个算法函数#xff0c;用于移除相邻的重复元素#xff0c;使每个相邻的元素在容器中保持唯一。它不会真正移除元素#xff0c;而是通… 声明本文内容生成自ChatGPT目的是为方便大家了解学习作为引用到作者的其他文章中。 std::unique 是 C 标准库中的一个算法函数用于移除相邻的重复元素使每个相邻的元素在容器中保持唯一。它不会真正移除元素而是通过重新排列元素来消除相邻的重复项并返回一个指向新结尾的迭代器。此算法通常和 std::erase 或者 std::erase-remove idiom 结合使用以实际移除不需要的元素。
语法
#include algorithmtemplate class ForwardIt
ForwardIt unique(ForwardIt first, ForwardIt last);template class ForwardIt, class BinaryPredicate
ForwardIt unique(ForwardIt first, ForwardIt last, BinaryPredicate p);参数
first, last表示要处理的范围的迭代器。p可选自定义的二元谓词用于定义 相等 的标准。
返回值
std::unique 返回一个迭代器指向删除相邻重复元素后的新结尾位置。容器中从该位置到 last 之间的元素仍然存在但它们的值是未定义的。
特点
std::unique 只移除相邻的重复元素。如果需要移除所有重复的元素通常需要先使用 std::sort 对容器排序。它通过重新排列容器中的元素将相邻重复的元素放置在一起并返回新范围的末尾迭代器。容器的大小不会实际改变。
示例
1. 基本使用移除相邻重复项
#include iostream
#include vector
#include algorithmint main() {std::vectorint vec {1, 1, 2, 3, 3, 4, 5, 5, 6};// 使用 std::unique 移除相邻的重复项auto new_end std::unique(vec.begin(), vec.end());// 打印结果std::cout Vector after unique: ;for (auto it vec.begin(); it ! new_end; it) {std::cout *it ;}std::cout std::endl;return 0;
}输出
Vector after unique: 1 2 3 4 5 6 2. 实际移除重复项结合 erase
#include iostream
#include vector
#include algorithmint main() {std::vectorint vec {1, 1, 2, 3, 3, 4, 5, 5, 6};// 使用 std::unique 移除相邻的重复项auto new_end std::unique(vec.begin(), vec.end());// 使用 erase 减少容器大小vec.erase(new_end, vec.end());// 打印结果std::cout Vector after erase: ;for (const auto num : vec) {std::cout num ;}std::cout std::endl;return 0;
}输出
Vector after erase: 1 2 3 4 5 6 3. 自定义谓词
你可以通过提供自定义的谓词来定义 相等 的标准。例如比较绝对值相等的元素
#include iostream
#include vector
#include algorithm
#include cmathint main() {std::vectorint vec {1, -1, 2, 3, -3, 4, 5, 5, 6};// 使用自定义谓词来移除相邻绝对值相等的元素auto new_end std::unique(vec.begin(), vec.end(), [](int a, int b) {return std::abs(a) std::abs(b);});// 使用 erase 减少容器大小vec.erase(new_end, vec.end());// 打印结果std::cout Vector after unique with custom predicate: ;for (const auto num : vec) {std::cout num ;}std::cout std::endl;return 0;
}输出
Vector after unique with custom predicate: 1 2 3 4 5 6 4. 非相邻重复元素的移除排序unique
std::unique 只移除相邻的重复元素。如果容器中存在非相邻的重复元素通常需要先排序。
#include iostream
#include vector
#include algorithmint main() {std::vectorint vec {1, 5, 2, 3, 3, 4, 5, 1, 6};// 对容器进行排序std::sort(vec.begin(), vec.end());// 使用 std::unique 移除所有重复的元素auto new_end std::unique(vec.begin(), vec.end());// 使用 erase 减少容器大小vec.erase(new_end, vec.end());// 打印结果std::cout Vector after sort and unique: ;for (const auto num : vec) {std::cout num ;}std::cout std::endl;return 0;
}输出
Vector after sort and unique: 1 2 3 4 5 6 总结
std::unique 是一个用于移除相邻重复元素的算法。它通过重新排列容器中的元素将不需要的重复元素移动到末尾并返回新的末尾位置。如果想要实际移除元素需要结合 erase 函数。如果容器中存在非相邻的重复元素通常需要先使用 std::sort 对容器进行排序。