Map in STL: Simplify Your C++ Coding

𝐌𝐲 𝐅𝐚𝐯𝐨𝐫𝐢𝐭𝐞 𝐓𝐨𝐨𝐥 𝐢𝐧 𝐒𝐓𝐋: 𝐦𝐚𝐩 When it comes to solving problems efficiently, one thing I keep coming back to is map in C++ STL. What is map? 𝐦𝐚𝐩 𝐢𝐬 𝐚𝐧 𝐚𝐬𝐬𝐨𝐜𝐢𝐚𝐭𝐢𝐯𝐞 𝐜𝐨𝐧𝐭𝐚𝐢𝐧𝐞𝐫 𝐭𝐡𝐚𝐭 𝐬𝐭𝐨𝐫𝐞𝐬 𝐝𝐚𝐭𝐚 𝐢𝐧 𝐤𝐞𝐲-𝐯𝐚𝐥𝐮𝐞 𝐩𝐚𝐢𝐫𝐬 𝐚𝐧𝐝 𝐤𝐞𝐞𝐩𝐬 𝐤𝐞𝐲𝐬 𝐚𝐮𝐭𝐨𝐦𝐚𝐭𝐢𝐜𝐚𝐥𝐥𝐲 𝐬𝐨𝐫𝐭𝐞𝐝. Example: {key → value} like {1 → 3} means number 1 appears 3 times — here 𝐢𝐭.𝐟𝐢𝐫𝐬𝐭 𝐠𝐢𝐯𝐞𝐬 1 (𝐤𝐞𝐲), 𝐢𝐭.𝐬𝐞𝐜𝐨𝐧𝐝 𝐠𝐢𝐯𝐞𝐬 3 (𝐟𝐫𝐞𝐪𝐮𝐞𝐧𝐜𝐲), and it is the iterator. Why? Because it makes life so much easier • 𝐀𝐮𝐭𝐨𝐦𝐚𝐭𝐢𝐜 𝐬𝐨𝐫𝐭𝐢𝐧𝐠 𝐨𝐟 𝐤𝐞𝐲𝐬 • 𝐄𝐚𝐬𝐲 𝐟𝐫𝐞𝐪𝐮𝐞𝐧𝐜𝐲 𝐜𝐨𝐮𝐧𝐭𝐢𝐧𝐠 • 𝐂𝐥𝐞𝐚𝐧 𝐚𝐧𝐝 𝐫𝐞𝐚𝐝𝐚𝐛𝐥𝐞 𝐜𝐨𝐝𝐞 • 𝐑𝐞𝐝𝐮𝐜𝐞𝐬 𝐜𝐨𝐦𝐩𝐥𝐞𝐱 𝐥𝐨𝐠𝐢𝐜 𝐢𝐧𝐭𝐨 𝐬𝐢𝐦𝐩𝐥𝐞 𝐥𝐢𝐧𝐞𝐬 The best part? Using map, we can solve multiple questions on LeetCode with the same pattern — especially problems based on: • 𝐅𝐫𝐞𝐪𝐮𝐞𝐧𝐜𝐲 𝐜𝐨𝐮𝐧𝐭𝐢𝐧𝐠 • 𝐃𝐮𝐩𝐥𝐢𝐜𝐚𝐭𝐞𝐬 / 𝐩𝐚𝐢𝐫𝐬 • 𝐇𝐚𝐬𝐡𝐢𝐧𝐠 𝐜𝐨𝐧𝐜𝐞𝐩𝐭𝐬 Recently, while solving a problem on counting “good pairs”, map helped me: • 𝐒𝐭𝐨𝐫𝐞 𝐟𝐫𝐞𝐪𝐮𝐞𝐧𝐜𝐢𝐞𝐬 𝐞𝐟𝐟𝐨𝐫𝐭𝐥𝐞𝐬𝐬𝐥𝐲 • 𝐀𝐩𝐩𝐥𝐲 𝐭𝐡𝐞 𝐬𝐢𝐦𝐩𝐥𝐞 𝐟𝐨𝐫𝐦𝐮𝐥𝐚: 𝐟 * (𝐟 - 1) / 2 • 𝐂𝐨𝐧𝐯𝐞𝐫𝐭 𝐚 𝐛𝐫𝐮𝐭𝐞-𝐟𝐨𝐫𝐜𝐞 𝐎(𝐧²) 𝐬𝐨𝐥𝐮𝐭𝐢𝐨𝐧 𝐢𝐧𝐭𝐨 𝐎(𝐧 𝐥𝐨𝐠 𝐧) Sometimes, it's not about writing complex code… it's about choosing the right data structure. Once you master map, you unlock solutions to many problems with the same approach What’s your go-to STL container? #cpp #stl #coding #datastructures #leetcode #programming #developers

  • text

To view or add a comment, sign in

Explore content categories