c++ - 删除向量c ++的重复元素
问题描述
所以.. 我有 2 个向量:xmax 和 ymax,它们代表点列表的 x 和 y 坐标。我想删除其中 xmax[i]==xmax[i-1] 和 ymax[i]==ymax[i-1] 的变量(所以......总之,我想删除重复的点坐标相同)。这是我正在使用的代码:
std::vector<double> xx, yy;
for (int i = 0; i < xmax.size(); i++) {
if (i > 0 && xmax[i] == xmax[i - 1] && ymax[i]==ymax[i-1])
continue;
xx.push_back(xmax[i]);
yy.push_back(ymax[i]);
}
但我想知道是否有一种简单的方法可以在不为此创建新向量的情况下删除变量。
解决方案
我建议切换到成对的单个向量(而不是两个单独的向量):
std::vector<std::pair<int, int>> points = {{1, 1}, {5, 2}, {5, 2}, {7, 10}};
然后你就可以使用std::unique()
.
如果你定义一个比较器函数:
bool point_compare(const std::pair<int, int> &p1, const std::pair<int, int> &p2) {
return p1.first == p2.first && p1.second == p2.second;
}
然后你可以std::unique()
像这样使用:
auto last = std::unique(points.begin(), points.end());
points.erase(last, points.end());
在此处查看实际操作:https ://ideone.com/fZM9b2
推荐阅读
- apache-kafka - 当前是否存在用于 CSV 文件的 Kafka Sink 连接器?
- android - Android 中的 URL 模式匹配
- ios - 从 MSOffice 应用程序保存新文档时,NSFileProvider importDocument 提供空文件的 fileURL
- javascript - Spring 应用停止读取 css 和 js 文件
- python - Django 1.11:在我的并行测试运行中,什么使“pickle”失败了?
- ios - stopMonitoringForRegion 是否仅停止重复区域或也停止原始区域?
- android - 如何使用 FileProvider 查看/显示 PDF 文件?仅显示空白屏幕
- css - 如何在SASS中将分数放在单位前面
- python-3.x - 如何确保 k 中簇的质心意味着算法不会每次都切换?
- .net - 从 dnn 9.1.0 专业版降级到 dnn 9.1.0 社区版