Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use a vector of indices to erase those indices of another vector

Tags:

c++

vector

I have two vectors, one is a vector of indices of the other vector that I would like to erase. Currently I am doing the following:

#include <vector>
#include <iostream>
#include <string>

int main() {
        std::vector<std::string> my_vec;
        my_vec.push_back("one");
        my_vec.push_back("two");
        my_vec.push_back("three");
        my_vec.push_back("four");
        my_vec.push_back("five");
        my_vec.push_back("six");

        std::vector<int> remove_these;
        remove_these.push_back(0);
        remove_these.push_back(3);

        // remove the 1st and 4th elements
        my_vec.erase(my_vec.begin() + remove_these[1]);
        my_vec.erase(my_vec.begin() + remove_these[0]);

        my_vec.erase(remove_these.begin(), remove_these.end());

        for (std::vector<std::string>::iterator it = my_vec.begin(); it != my_vec.end(); ++it)
                std::cout << *it << std::endl;

        return 0;
}

But I think this is inelegant and inefficient. Further, I think I have to be careful to sort my remove_these vector and start from the end (that's why I erase index 3 before index 0). I would like to have one erase command, something like

my_vec.erase(remove_these.begin(), remove_these.end());

But of course that won't work because my_vec.erase() expects iterators referring to the same vector.

like image 992
Xu Wang Avatar asked Dec 21 '22 11:12

Xu Wang


1 Answers

A known idiom to erase elements from a standard sequence is the erase/remove idiom. You first call the remove algorithm that will move all the elements you want to keep to the front of the sequence, then you erase the removed elements at the back of your sequence. In C++11 it looks like this:

std::vector< std::string > strings;
strings.erase(
    std::remove_if(
        strings.begin(), strings.end()
      , []( std::string const& s ) -> bool
        {
            return /*whether to remove this item or not*/;
        }
    )
  , strings.end()
);
like image 193
K-ballo Avatar answered Dec 24 '22 01:12

K-ballo