如何查找要从向量中删除的值,以及如何从辅助向量中删除相同的位置

How to find a value to remove from a vector, and remove the same position from a secondary vector?

本文关键字:向量 删除 位置 查找 何查找      更新时间:2023-10-16

我有 2 个向量,例如

 vector<int> set1;     // 4, 5, 2
 vector<string> set2;  // a, b, c

我想从set1中找到并删除5,并且由于它是第 2 项,因此也从set2中删除b

首先,一个叫做set1set2向量很奇怪。为什么不使用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/