簡體   English   中英

通過const成員函數對向量進行排序

[英]Sorting a vector by a const member function

我正在嘗試使用lambda函數對自定義類的向量進行排序,但是在某個地方,我得到了一個我不理解的廢棄const

我已經嘗試過在這里尋找答案,盡管許多人都提出了幾乎完全相同的問題,但似乎沒有一個是相同的問題。 我不禁止使用move構造函數,也不以這種形式調用非const成員/成員函數(至少我知道。顯然我做錯了。)我能想到的最接近的是返回非const成員的值,但是我通過const函數做到了,我明確地想做到這一點。 我希望面向公眾的成員函數不能更改任何內容,而面向私有的成員可以在內部進行更改(但不能由任何面向公眾的函數更改)。 我正在做的唯一真正奇怪的事情(我認為這對此沒有任何影響)是我的班級是不可復制的,並且具有不可復制的成員(移動很好)。

class MyClass{
 public:
  const SortByThis() { return internal_value; } //Edit: This declaration is the problem, as noted in the accepted answer.
  MyClass(SortByThis, BigNonCopyableDataStrcuture);
  MyClass(MyClass&)=delete; //No copy allowed. Only move.
 private:
  int internal_value;
  BigNonCopyableDataStructure_t big_structure;
}
std::vector<MyClass> vec;
DoFillVec(vec); //Vec now has many items but is not sorted

std::sort(vec.begin(), vec.end(), [](const MyClass &lhs, const MyClass &rhs){return lhs.SortByThis() < rhs.SortByThis();});
//This is where things scream at me.
//Project/Module.cc:226:95: error: passing ‘const Namespace::Module::MyClass’ as ‘this’ argument discards qualifiers [-fpermissive]

我希望這能對向量進行排序,但編譯器會抱怨我做錯了事,而我不知道我做錯了什么。 在這一點上,我被簡化為糾結,直到它編譯為止(並不是那種不舒服的感覺)。

SortByThis聲明不正確。 const放在函數之后,而不是之前:

int SortByThis() const { return internal_value; }

讓我們知道是否可以解決問題!

暫無
暫無

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

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