2014-11-05 79 views
0

我想要刪除元素,如果它的值與字符串「empty」匹配,那麼迭代完整的循環,但它不以這種方式工作。從矢量範圍中刪除特定元素

#include <iostream> 
#include <string> 
#include <vector> 
using namespace std; 

int main() 
{ 
    std::vector<std::string> myvector; 

    myvector.push_back("value"); 
    myvector.push_back("value"); 
    myvector.push_back("empty"); 
    myvector.push_back("value"); 
    myvector.push_back("value"); 
    myvector.push_back("empty"); 
    myvector.push_back("empty"); 

    int index = 0; 
    for(string input: myvector){ 
    if(input == "empty") 
     myvector.erase(myvector.begin()+index,myvector.begin()+index); 
    index++; 
    } 

    for(string input: myvector){ 
    cout << input << endl; 
    } 
    return 0; 
} 

但我們可以看到沒有東西被刪除?
輸出繼電器:

value 
value 
empty 
value 
value 
empty 
empty 

尋找類似下面,但不存在

myvector.erase(myvector.begin(),myvector.end(),"empty"); 

所以如何實現在更復雜?

+1

看[刪除,刪除成語(http://en.wikipedia.org/wiki/Erase-remove_idiom) – Jarod42 2014-11-05 10:45:50

回答

2

你應該使用std ::的remove_if這樣的:

myvector.erase(std::remove_if(myvector.begin(), myvector.end(), [](const std::string& string){ return (string == "empty"); }), myvector.end()); 
+1

沒必要用'的std :: remove_if'和拉姆達在這裏,爲什麼不乾脆用「std :: remove」的值爲「空」'? – Snps 2014-11-05 15:00:36

2
std::vector<std::string> myvector; 
    myvector.push_back("value"); 
    myvector.push_back("value"); 
    myvector.push_back("empty"); 
    myvector.push_back("value"); 
    myvector.push_back("value"); 
    myvector.push_back("empty"); 
    myvector.push_back("empty"); 
    auto it = std::remove_if(myvector.begin(), myvector.end(), 
    [](const std::string& s) 
    { 
     return (s== "empty"); 
    }); 
    myvector.erase(it, myvector.end()); 
  1. 使用remove_if把所有發現"empty"vector末。
  2. 使用返回iterator來清除它們。