如何找到要从向量中删除的值,并从辅助向量中删除相同的位置?

时间:2016-02-13 09:54:57

标签: c++ vector

我有2个载体,例如

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

我想从5中找到并删除set1,因为它是第2项,所以也从b移除set2

2 个答案:

答案 0 :(得分:3)

首先,名为set1set2向量很奇怪。为什么不使用std::set

无论如何,假设set2不小于set1,一个非常通用的解决方案是使用std::distance来计算查找结果与{{1}的开头之间的距离}}。然后,您只需将距离添加到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"; } } 较小或不存在5时的情况添加一些错误处理。

答案 1 :(得分:0)

我建议您使用这样的配对

options

推送示例

vector < pair < int,string > > set;

最后一个是你的问题,是如何删除所说的2和&#34; b&#34;从矢量。首先,你必须通过搜索来找到索引。

set.push_back(make_pair(1,"a"));
set.push_back(make_pair(2,"b"));
set.push_back(make_pair(3,"c"));

好的,在我们找到索引之后,现在使用vector :: erase擦除它。这是怎么做的。

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;
    }

你去,希望它有所帮助。

阅读来源:

http://www.cplusplus.com/reference/utility/pair/

http://www.cplusplus.com/reference/vector/vector/erase/