如何查找要从向量中删除的值,以及如何从辅助向量中删除相同的位置
How to find a value to remove from a vector, and remove the same position from a secondary vector?
我有 2 个向量,例如
vector<int> set1; // 4, 5, 2
vector<string> set2; // a, b, c
我想从set1
中找到并删除5
,并且由于它是第 2 项,因此也从set2
中删除b
。
首先,一个叫做set1
或set2
的向量很奇怪。为什么不使用std::set
?
无论如何,假设set2
不小于set1
,一个非常通用的解决方案是使用std::distance
来计算查找结果和set1
开始之间的距离。然后,您可以将距离添加到set2
的开头:
#include <vector>
#include <algorithm>
#include <iostream>
#include <string>
int main()
{
std::vector<int> set1 = { 4, 5, 2 };
std::vector<std::string> set2 = { "a", "b", "c" };
using std::begin;
using std::end;
// get iterator to first '5' element:
auto const set1_iter = std::find(begin(set1), end(set1), 5);
// how many steps does it take to go from start to the '5' element?
auto const distance = std::distance(begin(set1), set1_iter);
// go to same position in set2:
auto const set2_iter = begin(set2) + distance;
// use position to erase the element:
set2.erase(set2_iter);
for (auto&& element : set2)
{
std::cout << element << "n";
}
}
在实际代码中,您需要为set2
较小或不存在 5 的情况添加一些错误处理。
我建议你像这样使用对
vector < pair < int,string > > set;
推送示例
set.push_back(make_pair(1,"a"));
set.push_back(make_pair(2,"b"));
set.push_back(make_pair(3,"c"));
最后一个是你的问题,是如何从向量中删除所说的 2 和"b"。首先,您必须通过搜索来找到索引。
for(int x = 0; x < set.size(); x++)
if(set[x].first == 2){ //here we want delete data who have int of 2
idx = x; //save the index at variable idx
break;
}
好的,在我们找到索引后,现在使用 vector::erase 擦除它。这里该怎么做。
set.erase(set.begin()+idx);
好了,希望有帮助。
阅读来源 :
http://www.cplusplus.com/reference/utility/pair/
http://www.cplusplus.com/reference/vector/vector/erase/
相关文章:
- 迭代时从向量和内存中删除对象
- 如何在向量中删除 std::function<void()>?
- 移除和删除与向量中的条件匹配的指针
- 比较 2 个向量并从第二个向量中删除在第一个 - c++ 中找不到的元素
- 为什么通过 vector<reference_wrapper> 的元素删除引用的值<T>不会使向量无效?
- 如何在元组初始化向量中删除样板?
- 如何删除包含其他向量的向量?
- 从列表向量中删除无法按预期工作
- 从数组中删除非唯一值、保持顺序和不使用向量的最佳方法?
- 如何删除除 ArduinoSTL 的向量函数之外的所有函数
- 如何在具有特定条件的向量中删除所有元组?
- 删除指向抽象类的指针向量
- 从自定义数据类型向量中删除重复元素
- 防止我的向量在调用它的函数结束时被删除
- 从ints向量删除int的问题
- 使用find_if从向量删除所有偶数数字
- 崩溃,如果使用向量删除了一个嵌入式容器的destructor中删除char*成员
- 从向量删除重复元素
- 基元向量删除引发异常
- 如何使用指向每个元素的指针向量删除qcheckbox数组?