我有两个 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/