2012-12-30 53 views
3

我正在嘗試迭代向量並刪除對象的第一個匹配項。我一直在收到一個編譯錯誤(使用g ++),但是我正在以stackoverflow的答案和其他消息來源建議刪除它的方式將其刪除。可能有一些超級簡單的東西我錯過了,所以另一組眼睛也會很棒。C++中的向量迭代和刪除

#include <iostream> 
#include <vector> 
#include <assert.h> 
using namespace std; 

bool Garage::remove(const Car &car){ 
assert(!empty()); 

int size = v.size(); 
for(vector<Car>::const_iterator it = v.begin(); it != v.end(); ++it){ 
    if(it -> Car::make() == car.Car::make()){ 
     it = v.erase(it); 
     assert(v.size() == size - 1); 
     return true; 
    } 
} 
return false; 
} 

編譯錯誤是 錯誤:調用「的std ::矢量::擦除(常量汽車&)」

+0

請不要使用作業標籤。 [已過時](http://meta.stackexchange.com/questions/147100/the-homework-tag-is-now-officially-deprecated) – chris

+2

您應該搜索_erase/remove_成語... –

+0

錯誤似乎不符合您的代碼。你確定你的代碼沒有說'擦除(*)'或類似的東西嗎? –

回答

3

沒有匹配的功能你試圖使用常量性抹掉。由於您試圖修改矢量,請切換到常規迭代器。

for(vector<Car>::iterator it = v.begin(); it != v.end(); ++it){ 

這工作:

int main() 
{ 
    vector<int> ints; 

    for (vector<int>::iterator iter = ints.begin();iter != ints.end();++iter) 
    { 
     ints.erase(iter); 
    } 
} 

這不:

int main() 
{ 
    vector<int> ints; 

    for (vector<int>::const_iterator iter = ints.begin();iter != ints.end();++iter) 
    { 
     ints.erase(iter); 
    } 
} 

錯誤使用常量性時:

test.cpp:18:22: error: no matching function for call to ‘std::vector<int>::erase(std::vector<int>::const_iterator&)’ 
+0

我刪除了const,現在編譯。只需要測試一噸。 – Sams

+0

請注意,在遵循C++ 11標準的編譯器上,它*將*與'const_iterator'一起工作。 –

+1

@Bo Persson與哪個版本的gcc?我正在運行4.6.3(g ++ -std = C++ 0x),它不支持const_iterator。我看到它在這裏指定,但gcc不支持它呢? http://en.cppreference.com/w/cpp/container/vector/erase –

1

It appears,你需要使用find找到該元素的索引,然後erase它。我說「出現」,因爲我不是C++程序員。