簡體   English   中英

std::list remove_if 使用堆棧中的狀態

[英]std::list remove_if using state in stack

我想從具有線性復雜性的std::list刪除元素(只遍歷列表中的每個元素一次)。 我需要根據堆棧中變量的值來這樣做:

int somevalue= 5;
int count=0;
mylist.remove_if( 
    [](MyStructure* s)
    { 
        if (s->somefield==somevalue) 
        {
            count++;
            return true;
        }
        else
        return false;
    });

當然,這不起作用 - somevalue是堆棧中的變量。

我試過使用模板函數,只是為了意識到(在illegal operation on bound member function expression進行illegal operation on bound member function expression之后)在這種情況下你不能真正使用它們。 我知道我需要以某種方式關閉,所以我已經閱讀了這個問題,但是我還不能使用C++0x並且我沒有為我的用例調整另一個答案,因為我真的不明白是否有operator一些魔法。

或者,是否有某種方法可以根據迭代器的當前位置從列表中刪除元素(無需再次遍歷整個列表以查找元素)?

就 lambda 表達式(c++11 特性)而言,您可以像這樣按值捕獲somevalue[somevalue](...) {...}

你必須捕捉somevalue在lamdba表達式中使用它:

示例(住在這里):

struct MyStructure
{
    int somefield;
};

int main(int argc, char** argv) {

  std::list<MyStructure> my_list = { { 1 }, { 2 }, { 1 }, { 3 }, { 2 }, { 1 } };
  int somevalue = 2;
  my_list.remove_if( [somevalue](MyStructure s){ return s.somefield == somevalue; });
  //                   ^^^^^^
  //                   Capture      

  for(auto& s : my_list)
      std::cout << s.somefield << " ";
  return 0;
}

您需要捕獲示例代碼中的變量:

int somevalue= 5;
mylist.remove_if( [somevalue](MyStructure* s){ s->somefield==somevalue });

如果沒有 C++11 可以使用,你需要自己制作函子:

// For static constant check
template <int CheckValue>
struct Equal {
    operator()(const MyStructure* s) { return s->somefield == CheckValue; }
};

mylist.remove_if(Equal<5>);

..or..

// For dynamic constant check as the sample code
struct Equal {
    Equal(int check_value) : m_check_value(check_value) {}
    operator()(const MyStructure* s) { return s->somefield == m_check_value; }
private:
    int m_check_value;
};

mylist.remove_if(Equal(somevalue));

迭代元素以確定要刪除的元素。 使用erase刪除標識的元素並繼續從返回的迭代器進行迭代。

類似的東西:

int somevalue=5;
std::list<MyStructure*> myList;
// ...
std::list<MyStructure*>::iterator it=myList.begin();
while(it!=myList.end())
{
  if ((*it)->somefield==somevalue)
  {
    it = myList.erase(it);
  }
  else
  {
    ++it;
  }
}

暫無
暫無

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

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