简体   繁体   中英

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

I have 2 vectors, for eg

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

I want to find and remove 5 from set1 and and since it's the 2nd item, remove b from set2 as well.

First of all, a vector called set1 or set2 is strange. Why not use std::set ?

Anyway, supposing that set2 is not smaller than set1 , a very generic solution would be to use std::distance to calculate the distance between the find result and the start of set1 . You can then just add the distance to the start of 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";
    }
}

In real code, you will want to add some error handling for the case when set2 is smaller or when 5 does not exist.

I suggest you to use pair like this

vector < pair < int,string > > set;

Example of push

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

And the last is your question, is how to erase said 2 and "b" from the vector. First you got to find the index by searching it.

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

Ok, after we have find the index, now erase it using vector::erase. Here how to do it.

set.erase(set.begin()+idx);

There you go, hope it help.

Reading source :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM