I've just started learning STL containers, and I cannot understand why std::multimap exists. With std::map, we can access values by user-defined keys, but with std::multimap we cannot do that as the latter does not even have an overloaded operator[] and the same key can be mapped to several different values. To me, this looks like std::multimap is essentialy just something like std::multiset<std::pair<K, V>> with the Compare function operating on the K and we lose the main feature of a map which is the ability to access elements by key (as I see it). I've found this post, but still couldn't comprehend the usecases given here. Could someone please give me several examples when we would use std::multimap?
What is the usage of std::multimap?
2.9k Views Asked by Kaiyakha At
1
There are 1 best solutions below
Related Questions in C++
- How to immediately apply DISPLAYCONFIG_SCALING display scaling mode with SetDisplayConfig and DISPLAYCONFIG_PATH_TARGET_INFO
- Why can't I use templates members in its specialization?
- How to fix "Access violation executing location" when using GLFW and GLAD
- Dynamic array of structures in C++/ cannot fill a dynamic array of doubles in structure from dynamic array of structures
- How do I apply the interface concept with the base-class in design?
- File refuses to compile std::erase() even if using -std=g++23
- How can I do a successful map when the number of elements to be mapped is not consistent in Thrust C++
- Can std::bit_cast be applied to an empty object?
- Unexpected inter-thread happens-before relationships from relaxed memory ordering
- How i can move element of dynamic vector in argument of function push_back for dynamic vector
- Brick Breaker Ball Bounce
- Thread-safe lock-free min where both operands can change c++
- Watchdog Timer Reset on ESP32 using Webservers
- How to solve compiler error: no matching function for call to 'dmhFS::dmhFS()' in my case?
- Conda CMAKE CXX Compiler error while compiling Pytorch
Related Questions in DICTIONARY
- Memoization yields slower results
- Dynamic Nested Multi-Dimensional Arrays in Rust
- What is 'Invalid Load Key, '\x00'
- tryin to write a function that searches for SSN in a dict, and if that SSN is found, to retrieve all the data associated with that SSN
- Soft list based on another list
- set custom location on tap on screen using flutter_map
- Creaating a new Key Value dict from previous dict
- How can I sort different elements based on keywords?
- Storing user inputs as parameters for a function
- How to make a map in swift and how to make an icon where your location bubble is?
- How to convert Map<string,boolean> to {key: string; value: boolean;}[]?
- List append dictionary - handling missing data
- I have a dictionary of Pandas dataframes, how would I write them to separate sheets in an Excel file using openpyxl
- Pipe broken exception when attempting to send multiple messages from client to server in C#
- Is there a function in pandas which lets you create columns for dictionary key + value pairs efficiently?
Related Questions in STL
- Why my code is working on everything except one instance?
- Why does the map size change?
- C++ ordered map optimized with index access
- Circular extention to std::array
- Is there a chance to use a custom std::pmr::polymorphic_allocator to make std::unordered_map’s buckets implemented as arrays?
- STL: Keeping Only Unique String Characters AND Preserving Order
- Importing <filesystem> in gcc
- Are there any iterator invalidation rules for <algorithms> operations?
- Check if Array Is Sorted and Rotated on LeetCode
- std::shared_mutex::unlock_shared() blocks even though there are no active exclusive locks on Windows
- could the type of std::map's key be double or float?
- How to implement an iterator for a two leveled map in C++?
- Why does priority_queue use greater<> for ascending order?
- Scope of C++ references and STL containers
- Implement Non Copyable Non Moveable wrapper for map/vector etc
Related Questions in MULTIMAP
- Java Map with Multimap values - how to efficient split the true entries from the false ones
- Need for lock on key when trying to update Multimap value
- Error in custom comparator for multimap stl c++11
- Best structure of Multiple indexed map
- Search by value in a multimap in O(log(n)) complexity
- How do I remove a specific item from my multimap?
- how to let jackson deserialize guava multimap using the '@class' field inside json to deside the target class?
- How to calculate average from Collection of HashMap<String, Double>
- Iterate over all the elements in a std::multimap with the same key
- Finding a key-value-pair within a std::multimap with key of type int
- Why can't IDE find the map I declared already in Guava Multimap using Enum?
- How to print the matching value of key from (Google Guava) Multimap?
- Multimap of pointers as a class member on the heap
- Unmodifiable Multimap
- c++ extract member of a key of a std::multiset into a std::vector without having a getter
Trending Questions
- UIImageView Frame Doesn't Reflect Constraints
- Is it possible to use adb commands to click on a view by finding its ID?
- How to create a new web character symbol recognizable by html/javascript?
- Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
- Heap Gives Page Fault
- Connect ffmpeg to Visual Studio 2008
- Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
- How to avoid default initialization of objects in std::vector?
- second argument of the command line arguments in a format other than char** argv or char* argv[]
- How to improve efficiency of algorithm which generates next lexicographic permutation?
- Navigating to the another actvity app getting crash in android
- How to read the particular message format in android and store in sqlite database?
- Resetting inventory status after order is cancelled
- Efficiently compute powers of X in SSE/AVX
- Insert into an external database using ajax and php : POST 500 (Internal Server Error)
Popular # Hahtags
Popular Questions
- How do I undo the most recent local commits in Git?
- How can I remove a specific item from an array in JavaScript?
- How do I delete a Git branch locally and remotely?
- Find all files containing a specific text (string) on Linux?
- How do I revert a Git repository to a previous commit?
- How do I create an HTML button that acts like a link?
- How do I check out a remote Git branch?
- How do I force "git pull" to overwrite local files?
- How do I list all files of a directory?
- How to check whether a string contains a substring in JavaScript?
- How do I redirect to another webpage?
- How can I iterate over rows in a Pandas DataFrame?
- How do I convert a String to an int in Java?
- Does Python have a string 'contains' substring method?
- How do I check if a string contains a specific word?
First note that
std::map::operator[]is a little quirky. It is not the way to access elements in the map. Insteadstd::map::operator[]potentially inserts an element into the map and then returns a reference to either the element that was already present before or to the newly inserted. This may seem like splitting hairs, but the difference matters. The way to access a mapped_value given a key in astd::mapisstd::map::find.std::multimaphas afindas well. No big difference with respect to that.std::map::athas not counterpart instd::multimapbecausestd::map::atreturns a reference to the mapped_value for the given key, but in the multimap there can be more than one mapped_value for the same key, so it isnt obvious what astd::multimap::atshould return if it existed. Finding and accessing elements can be done withfindfor both maps.A
std::multimap<K,V>can be compared to astd::map<K,std::vector<V>>but with the interface you'd expect when you want to map more than a single value to the same key. For examplestd::multimapiterators lets you iterate all key-value pairs in the multimap in one go. With the map of vectors you'd have to use the maps iterators and the vectors iterators. Using the map of vectors with standard algorithms is rather cumbersome. Further,std::multimap::countreturns the number of elements for a given key. With the map of vectors you would have to first find the vector for given key and call itssize. This list is not complete, but I hope the difference gets clear.One example for a multimap could be inhabitants of houses. In the same house lives more than one person. If you want to map street number to person you could use a multimap.
More generally, if you have a collection / container of elements and you want to divide them into distinct groups, you can use a multimap. A common use of
std::map(orstd::unordered_map) is to count frequencies, eg:This counts how many elements of
some_containerare divisible by 3, without remainder, with remainder 1, or with remainder 2. If you want to know the elements rather than only count them you can use astd::multimap.