我知道這個標題很混亂,我只是用這麼幾個字來描述它。 考慮以下代碼:從矢量中刪除一個字符串<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;
}
}
正如你所看到的,我只是做了其他環肚裏反向。
你應該從更大的索引中刪除,以降低之一。 – Jarod42
@ Rakete1111是的,現在修復了它 –
你不初始化'n'? –