Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
🔴 Advanced  ·  Lesson 57

set and map in STL

Ordered Associative Container Model

set और map key द्वारा data retrieve करते और comparator से order maintain करते हैं। Default std::less normally ascending order देता है।

ContainerDataKeys
setKeyUnique
multisetKeyEquivalent allowed
mappair<const Key,T>Unique
multimapKey-valueEquivalent allowed

Core search/insert/erase O(log n) हैं। Standard specific tree mandate नहीं करता। vector vs map decision guide देखें।

std::set: Unique Ordered Values

std::set<int> rolls{104,101,104,103};
for(int roll:rolls) std::cout<<roll<<' ';
auto [pos,inserted]=rolls.insert(102);
101 103 104

Duplicate 104 insert नहीं हुआ। Set iterator key को const access देता है; in-place change ordering तोड़ सकता है। Key बदलने के लिए erase/reinsert करें। Repeated equivalent values चाहिए तो multiset लें।

std::map: Unique Key और Value

std::map<std::string,int> marks{
 {"Sara",91},{"Aman",78}};
marks.insert_or_assign("Aman",83);
marks.try_emplace("Kabir",84);
for(const auto& [name,mark]:marks)
 std::cout<<name<<':'<<mark<<' ';
Aman:83 Kabir:84 Sara:91

insert_or_assign insert या replace करता है; try_emplace missing key पर ही construct करता है। Iterator में key const लेकिन mapped value modifiable है।

Lookup और Access

OperationResultInsert?
findIterator/endNo
contains C++20boolNo
count0/1No
atValue/exceptionNo
operator[]Mapped referenceMissing पर yes
lower_boundNot-before keyNo
if(auto it=marks.find("Sara");it!=marks.end())
 std::cout<<it->second;
if(!marks.contains("Riya")) std::cout<<"Not found";
Read-only test में marks["Riya"] use करने से missing key insert हो जाएगी।

Comparators और Key Rules

Comparator strict weak ordering दे। दो keys equivalent हैं जब कोई भी दूसरे से पहले compare न हो; यह जरूरी नहीं कि == जैसा हो।

struct ByLengthThenText{
 bool operator()(const std::string& a,
                 const std::string& b)const{
  if(a.size()!=b.size()) return a.size()<b.size();
  return a<b;
 }
};

<=, random result, time या mutable state comparator में गलत हैं। Stored keys के दौरान result consistent रहे।

Insertion, Erasure और Iterator Safety

marks.emplace("Riya",86);
marks.erase("Aman");
for(auto it=marks.begin();it!=marks.end();){
 if(it->second<40) it=marks.erase(it);
 else ++it;
}
  • Insert/emplace existing handles invalidate नहीं करते।
  • Erase केवल erased element handles invalidate करता है।
  • erase(iterator) next iterator देता है।
  • end को dereference और erased iterator reuse न करें।

unordered_map average O(1) lookup दे सकता है लेकिन sorted order नहीं और worst O(n) संभव है।

Complete Word-Frequency Lab

std::vector<std::string> words{
 "code","learn","code","cpp","learn","code"};
std::set<std::string> unique_words;
std::map<std::string,int> frequency;
for(const std::string& word:words){
 unique_words.insert(word);
 ++frequency[word];
}
Unique: code cpp learn Frequency: code=3 cpp=1 learn=2

यहां [] intentional है क्योंकि missing count zero से शुरू होकर increment होना चाहिए। दोनों containers lexical key order में iterate करते हैं।

Mistakes, Practice और Review

MistakeCorrection
Insertion order expectComparator order
Read lookup में []find/contains/at
Duplicate keys expectMulti-container/model
Comparator <=Strict weak ordering
Key in-place changeErase/reinsert
Erased iterator useReturned next iterator

Practice: phone book, word counter, unique roll register, lower_bound score query और custom year/roll key बनाएं।

  1. Set या relation?
  2. Unique/repeated keys?
  3. Comparator valid?
  4. Lookup inserts?
  5. Required order?
  6. Erased handles discarded?

Authoritative संदर्भ

Order, equivalence, complexity और iterator rules current draft से verified हैं। STL architecture भी पढ़ें।

अक्सर पूछे जाने वाले प्रश्न (FAQ)

C++ set और map में क्या अंतर है?
set unique keys को elements की तरह रखता है। map unique ordered key के साथ mapped value जोड़ता है। दोनों comparison object से order maintain करते हैं।
क्या std::set और std::map हमेशा sorted होते हैं?
Iteration container comparator के order में होती है; default std::less normally ascending key order देता है। Valid custom strict weak ordering इसे बदल सकता है।
Missing key पर map operator[] क्या करता है?
यह उस key के लिए value-initialized mapped value insert करके reference लौटाता है। Read-only lookup में find, contains या at लें।
क्या set या map duplicate keys रख सकता है?
set और map unique keys रखते हैं। Equivalent keys के लिए multiset/multimap या map> जैसा suitable model चुनें।
क्या insertion set/map iterators invalidate करता है?
Normal insert/emplace existing iterators/references invalidate नहीं करता। Erase केवल erased elements के handles invalidate करता है।
← Back to C++ Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

अगला topicIterators in STL आपकी प्रगति: 57 / 81 (70%) · Lesson 58 / 81 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें