c++ - 使用一个索引 vector 来删除另一个 vector 的那些索引

标签 c++ vector

我有两个 vector ,一个是我想删除的另一个 vector 的索引 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;
}

但我认为这是不优雅且低效的。此外,我认为我必须小心地对我的 remove_these vector 进行排序并从末尾开始(这就是为什么我在索引 0 之前删除索引 3)。我想要一个删除命令,比如

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

但这当然行不通,因为 my_vec.erase() 期望迭代器引用相同的 vector 。

最佳答案

从标准序列中删除元素的已知习惯用法是删除/删除习惯用法。您首先调用 remove 算法,该算法会将您想要保留的所有元素移动到序列的前面,然后您在序列的后面删除 删除的元素。在 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()
);

关于c++ - 使用一个索引 vector 来删除另一个 vector 的那些索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14094180/

相关文章:

取消引用指向结构 vector 的指针时的c++段错误

performance - `modify` 什么时候复制向量?

c++ - 在 C++ 中可以使用构造函数将 2D Vector 初始化为单行吗?

vector - 无法返回字符串切片向量 : borrowed value does not live long enough

c++ - 哪种方法可以在不阻塞主线程的情况下并行处理多个作业

c++ - 证明 rand() 可以返回 0 的在线资源?

c++ - Arduino函数在调用其他函数后一直循环

c++ - 模板类模板方法特化

C++ 零初始化具有可变数组长度的模板数组

c++ - 创建大量对象指针