簡體   English   中英

C ++-按自定義數據類型向量的值刪除元素

[英]C++ - Removing element by value of custom data type vector

我正在嘗試按值刪除自定義數據類型向量的向量元素。 如果我使用像int等這樣的簡單數據類型而不是hello數據類型,它將很好地工作。

#include <iostream>
#include <vector>
#include <algorithm>

class hello
{

public:
    hello() {
        x = false;
    }
    bool x;
};

int main() {

   hello f1;
   hello f2;
   hello f3;

   std::vector <hello> vector_t;

   vector_t.push_back(f1);
   vector_t.push_back(f2);
   vector_t.push_back(f3);

   for (unsigned int i = 0; i < vector_t.size(); i++)
       {
       if (vector_t[i].x)
       {
            vector_t.erase(std::remove(vector_t.begin(), vector_t.end(), i), vector_t.end());
        }
    }

    return 0;
}

它顯示一個錯誤:

二進制'==':未找到采用'hello'類型的左操作數(或沒有可接受的轉換)的運算符vector_test

看起來您想在.x成員為true的情況下更喜歡使用remove_if

vector_t.erase(std::remove_if(vector_t.begin(), vector_t.end(), [](const hello &h) { return h.x; }), vector_t.end());

for循環和if條件不是必需的,因此不需要這種方式。

remove嘗試查找所有與您傳遞給它的元素進行比較的元素。 如果不告訴編譯器如何將hello對象與整數i值進行比較,則它將無法執行此操作。

您可能想做的就是在滿足您的條件的情況下刪除向量的第i個元素:

for (unsigned int i = 0; i < vector_t.size(); i++)
{
    if (vector_t[i].x)
    {
        vector_t.erase(vector_t.begin() + i);
        --i; // The next element is now at position i, don't forget it!
    }
}

最慣用的方式是使用std::remove_if ,如acgraig5075的答案所示。

它顯示一個錯誤:

binary '==': no operator found which takes a left-hand operand of type 'hello' (or there is no acceptable conversion) vector_test

您可以為您的類提供明顯缺少的運算符== ,它將解決此問題:

bool operator==(hello const &h)
{
    return this->x == h.x;
} 

您的刪除/擦除操作應如下所示:

vector_t.erase(std::remove(vector_t.begin(), vector_t.end(), vector_t[i]), vector_t.end());

演示: https : //ideone.com/E3aV76

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM