从矢量中删除一个字符串在矢量中定义的索引

问题描述:

我知道这个标题很混乱,我只是用这么几个字来描述它。 考虑以下代码:从矢量中删除一个字符串<string>在矢量中定义的索引<int>

#include <vector> 
#include <string> 

using std::string; 
using std::vector; 

int main() { 
    vector<string> s = { "foo", "bar", "random_word" }; 
    vector<int> i = { 0, 1 }; 
    for (int n = 0; n < i.size(); n++) { 
     s.erase(s.begin() + (i[n])); 
    } 
} 

我想从另一个向量i的基础上删除索引矢量s的项目。实际的程序比这个更复杂,但是用几句话来说,那个循环崩溃了(尽管它使用Visual C++编译得很好)。

编辑:这是导致问题的实际代码:

// The vector in which the elements to be deleted are defined consists of 
// { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 } (the 
// name is i) 
// The other vector (s) consists of 
// { "Bancheri", "Bertagna", "Buzzoni", "Canepa", "De Vita", "Di Bella", 
// "Drago", "Esposito", "Fossati", "Francini", "Frontini", "Lorenzi", 
// "Marusceac", "Miscio", "Padovani", "Scarfo'", "Sieni", "Thea Cioni", 
// "Zunino" }; 
} 
for (int p = 0; p < i.size(); p++) { 
     s.erase(s.begin() + (s[i])) 
} 

// This is how I fixed it: 

{ 
     int r = i.size() - 1; 
     while (r > 0) { 
      s.erase(s.begin() + i[r]); 
      r -= 1; 
     } 
} 

正如你所看到的,我只是做了其他环肚里反向。

+2

你应该从更大的索引中删除,以降低之一。 – Jarod42

+0

@ Rakete1111是的,现在修复了它 –

+3

你不初始化'n'? –

这种方法的问题是,一旦i[n]的项目被删除,它后面的所有索引就会移回一位。

为了让这个程序运行,排序i,并从最大到最小迭代。

+1

没错。 '的std ::排序(i.begin(),i.end(),标准::更大());'在进入循环之前。 – WhozCraig

+0

@WhozCraig我不知道这是什么代码的含义 –

+0

@TommasoTheaCioni它降序排列的容器。 –

正如已经指出的那样,崩溃的原因是索引失效 - 在删除i[n]的第th个元素后,所有大于i[n]的索引都必须减1。

通过以降序遍历索引的容器,确保没有在任何时刻比i[n]没有索引更大,因此没有必要调整其他索引,所以排序i没有解决这个问题。

但是由于std::vector是一个连续的数组,因此逐个擦除元素通常不是一个好主意。根据你的情况,这也很容易重新排列的代码来完成所有的擦除一气呵成:

std::sort(i.begin(),i.end()); 
i.push_back(s.size()); //just to make sure the whole vector is visited 
auto iter = s.begin(); 
int current_index = 0; 
for(int index : i) 
{ 
    while(current_index < index) 
    { 
     *(iter++) = s[current_index++]; 
    } 
    current_index++; 
} 
s.erase(iter, s.end()); 

如果你能负担得起代表元素,通过一定的值,例如被删除一个空字符串,它变得更好:

for(int index : i) 
    s[index] = ""; 
s.erase(std::remove(s.begin(),s.end(),""),s.end());