문제

나는 다음과 같은 간단한 예제는 내가 원하는 전화 std::for_each 에는 개체의 컬렉션은 복사할 수 없:

class A {
public:
    A() : x(0) {}
    A(const A&) = delete;

private:
    int x;
};

void func() {
    std::vector<A> v(10);
    std::map<int, A> m;

    // works as expected
    std::for_each(begin(v), end(v), [](const A& a) { /* do nothing */ });

    // error calling copy constructor
    std::for_each(begin(m), end(m), [](const std::pair<int, A>& a) { /* do nothing */ });
}

면으로 모든 것 std::vector, 으로 작동합니다 내가 예상되지만,사용하는 경우 std::map, 갑자기 std::for_each 원화(삭제)사본을 생성자입니다.왜?나는 생각이 나는 단순히 얻을 참조하여 페이지에 저장되지도 않고,필요한 모든 복사본입니다.

도움이 되었습니까?

해결책

문제는 std::mapstd::pair<const Key, Value> 으로 내부 값을 입력.보다 명시적으로 이를 지정하는 표준 라이브러리 용기를 추출할 수 있에서 이 콘테이너 유형:

에서는 C++11 지(동일에서는 C++98,하지만 당신은 것을 사용하는 함수 개체가 아닌 내부 람다 for_each, 고,또한 사용 typedefusing =):

using value_type = std::map<int, A>::value_type;
std::for_each(begin(m), end(m), [](value_type const& a) { /* do nothing */ });

C++에서 14 마:

std::for_each(begin(m), end(m), [](auto const& a) { /* do nothing */ });

의 사용 auto 내부에는 람다에서 지원 소 3.4,Visual Studio2013 월 CTP,그리고 GCC4.9.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top