我有两个向量,其中一个是另一个向量的索引向量,我想要删除它。目前我正在执行以下操作:
#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
向量,并从末尾开始删除(这就是为什么我在索引0之前删除索引3)。我想要一个删除命令,类似于
my_vec.erase(remove_these.begin(), remove_these.end());
当然,这样做是行不通的,因为my_vec.erase()
需要引用同一个向量的迭代器。