Expensive use of map instead of set
The key for a map is member of the object being inserted, resulting in redundant map key
Since R2024b
Description
This defect occurs when you use a member of an object as a key when inserting the object in a map container. Consider this code:
class Person { public: std::string name; int age; double height; //... }; void InsertPerson(std::map<std::string, Person> &map, const Person &person) { map[person.name] = person; // Defect }
InsertPerson()
inserts an object of class Person
and uses the member Person::name
as the key. Because a member of the inserted value is used as the key, Polyspace® reports this defect. This checker applies to inappropriate use of std::map
, std::multimap
, std::unordered_multimap
, and std::unordered_map
.Risk
Using a member of an object inserted in a map container as the key for that object results in redundant copies of same data, which is inefficient, especially if the key is expensive to copy. This practice can also indicate inappropriate choice of container.
Fix
To look up objects using a members of the object, use set containers such as
std::set
or std::unordered_set
instead of map
containers.
Performance improvements might vary based on the compiler, library implementation, and environment that you are using.
Examples
Result Information
Group: Performance |
Language: C++ |
Default: Off |
Command-Line Syntax:
EXPENSIVE_USE_OF_MAP_INSTEAD_OF_SET
|
Impact: Low |
Version History
Introduced in R2024b
See Also
Topics
- Interpret Bug Finder Results in Polyspace Desktop User Interface
- Interpret Bug Finder Results in Polyspace Access Web Interface (Polyspace Access)
- Address Results in Polyspace User Interface Through Bug Fixes or Justifications
- Address Results in Polyspace Access Through Bug Fixes or Justifications (Polyspace Access)