使用索引向量来擦除另一个向量的索引

Xu *_*ang 4 c++ vector

我有两个向量,一个是我想要擦除的另一个向量的索引向量.目前我正在做以下事情:

#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;
}
Run Code Online (Sandbox Code Playgroud)

但我认为这是不优雅和低效的.此外,我认为我必须小心对remove_these矢量进行排序并从最后开始(这就是我在索引0之前擦除索引3的原因).我想有一个擦除命令,类似于

my_vec.erase(remove_these.begin(), remove_these.end());
Run Code Online (Sandbox Code Playgroud)

但当然这不会起作用,因为my_vec.erase()期望迭代器引用相同的向量.

K-b*_*llo 6

从标准序列中擦除元素的已知习语是擦除/移除习语.您首先调用remove算法,将所有要保留的元素移动到序列的前面,然后erase移除序列后面的已删除元素.在C++ 11中,它看起来像这样:

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()
);
Run Code Online (Sandbox Code Playgroud)