반응형
람다로 정렬하는 방법?
sort(mMyClassVector.begin(), mMyClassVector.end(),
[](const MyClass & a, const MyClass & b)
{
return a.mProperty > b.mProperty;
});
인스턴스 메서드를 바인딩하는 대신 람다 함수를 사용하여 사용자 지정 클래스를 정렬하고 싶습니다. 그러나 위의 코드는 오류를 생성합니다.
오류 C2564 : 'const char *': 내장 유형으로의 함수 스타일 변환은 하나의 인수 만 사용할 수 있습니다.
그것은 함께 잘 작동합니다 boost::bind(&MyApp::myMethod, this, _1, _2)
.
알았다.
sort(mMyClassVector.begin(), mMyClassVector.end(),
[](const MyClass & a, const MyClass & b) -> bool
{
return a.mProperty > b.mProperty;
});
> 연산자가 (문서에 따라) 부울을 반환했다고 가정했습니다. 그러나 분명히 그렇지 않습니다.
많은 코드에 다음과 같이 사용할 수 있습니다.
#include<array>
#include<functional>
int main()
{
std::array<int, 10> vec = { 1,2,3,4,5,6,7,8,9 };
std::sort(std::begin(vec ), std::end(vec ), [](int a, int b) {return a > b; });
for (auto item : vec)
std::cout << item << " ";
return 0;
}
"vec"를 귀하의 클래스로 바꾸십시오.
"a.mProperty> b.mProperty"행에 문제가있을 수 있습니까? 작동하려면 다음 코드가 있습니다.
#include <algorithm>
#include <vector>
#include <iterator>
#include <iostream>
#include <sstream>
struct Foo
{
Foo() : _i(0) {};
int _i;
friend std::ostream& operator<<(std::ostream& os, const Foo& f)
{
os << f._i;
return os;
};
};
typedef std::vector<Foo> VectorT;
std::string toString(const VectorT& v)
{
std::stringstream ss;
std::copy(v.begin(), v.end(), std::ostream_iterator<Foo>(ss, ", "));
return ss.str();
};
int main()
{
VectorT v(10);
std::for_each(v.begin(), v.end(),
[](Foo& f)
{
f._i = rand() % 100;
});
std::cout << "before sort: " << toString(v) << "\n";
sort(v.begin(), v.end(),
[](const Foo& a, const Foo& b)
{
return a._i > b._i;
});
std::cout << "after sort: " << toString(v) << "\n";
return 1;
};
출력은 다음과 같습니다.
before sort: 83, 86, 77, 15, 93, 35, 86, 92, 49, 21,
after sort: 93, 92, 86, 86, 83, 77, 49, 35, 21, 15,
참고 URL : https://stackoverflow.com/questions/5122804/how-to-sort-with-a-lambda
반응형
'programing tip' 카테고리의 다른 글
C ++에서 예외가 작동하는 방식 (뒤에서) (0) | 2020.08.08 |
---|---|
JPA / Hibernate에서 flush ()의 올바른 사용 (0) | 2020.08.08 |
Vim 사용자 여러분, 오른손은 어디에 있습니까? (0) | 2020.08.08 |
크롬 확장에서 jQuery를 사용하는 방법? (0) | 2020.08.08 |
연결 목록은 어떤 상황에서 유용합니까? (0) | 2020.08.08 |