2013-05-02 10 views
8

मैं नीचे दिए गए उदाहरण में जैसे std :: मानचित्र का उपयोग करने की कोशिश कर रहा हूँ का उपयोग करते समय:एल-मूल्य स्थिरांक वस्तु को निर्दिष्ट std :: नक्शा

#include <map> 
#include <algorithm> 

int wmain(int argc, wchar_t* argv[]) 
{ 
    typedef std::map<int, std::wstring> TestMap; 
    TestMap testMap; 
    testMap.insert(std::make_pair(0, L"null")); 
    testMap.insert(std::make_pair(1, L"one")); 
    testMap.erase(std::remove_if(testMap.begin(), testMap.end(), [&](const TestMap::value_type& val){ return !val.second.compare(L"one"); }), testMap.end()); 
    return 0; 
} 

और मेरे संकलक (VS2010) मेरे देता है संदेश निम्न:

>c:\program files\microsoft visual studio 10.0\vc\include\utility(260): error C2166: l-value specifies const object 

1>   c:\program files\microsoft visual studio 10.0\vc\include\utility(259) : while compiling class template member function 'std::pair<_Ty1,_Ty2> &std::pair<_Ty1,_Ty2>::operator =(std::pair<_Ty1,_Ty2> &&)' 
1>   with 
1>   [ 
1>    _Ty1=const int, 
1>    _Ty2=std::wstring 
1>   ] 
1>   e:\my examples\с++\language tests\maptest\maptest\maptest.cpp(8) : see reference to class template instantiation 'std::pair<_Ty1,_Ty2>' being compiled 
1>   with 
1>   [ 
1>    _Ty1=const int, 
1>    _Ty2=std::wstring 
1>   ] 

मुझे समझ में नहीं आ रहा है कि ऑपरेटर = क्यों कहा जाता है हालांकि मैं संदर्भ में लैम्ब्डा-फ़ंक्शन में वैल पास करता हूं। क्या आप समझा सकते हैं कि मैं क्या गलत कर रहा हूं?

+0

त्रुटि संदेश लाइन 8 पर है, लैम्ब्डा लाइन 10 पर है। ऐसा लगता है कि जोड़ी असाइनमेंट 'insert() 'में हो रहा है, और लैम्ब्डा से असंबंधित है। – MSalters

+1

[मैप, लैम्ब्डा, हटाएं \ _if] के संभावित डुप्लिकेट (http://stackoverflow.com/questions/9515357/map-lambda-remove-if) – MSalters

उत्तर

12

तुम एक साहचर्य कंटेनर के साथ std::remove_if उपयोग नहीं कर सकते, क्योंकि वह एल्गोरिथ्म बाद में लोगों के साथ हटा दिया तत्वों अधिलेखन के द्वारा काम करता है: समस्या है कि यहाँ एक नक्शा की चाबी को रोकने के लिए निरंतर कर रहे हैं, यह है कि आप (या std::remove_if एल्गोरिथ्म) कंटेनर के आंतरिक क्रम के साथ गड़बड़ करने से।

सशर्त मानचित्र से तत्वों को निकालने के लिए नहीं बल्कि ऐसा करते हैं:

for (auto iter = testMap.begin(); iter != testMap.end();) 
{ 
    if (!iter->second.compare(L"one")) // Or whatever your condition is... 
    { 
     testMap.erase(iter++); 
    } 
    else 
    { 
     ++iter; 
    } 
} 

यहाँ एक live example है।

संबंधित मुद्दे