49 lines
1.2 KiB
Plaintext
49 lines
1.2 KiB
Plaintext
== Why is this an issue?
|
|
|
|
{cpp}20 introduces the member function ``++contains++`` on associative containers to check if an equivalent to a specific key already exists in the container.
|
|
|
|
|
|
Calling this function can replace previous ways to check if a key is present in a container:
|
|
|
|
* call ``++find()++`` and check that its result is not the end of the container. This was quite verbose.
|
|
* call ``++count()++``. This did not clearly express the intent and was not optimal in terms of performance for containers that allow a key to be present multiple times.
|
|
|
|
This rule raises an issue when `contains` could be used to simplify the code.
|
|
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,cpp,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
void f1(std::set<int> &s) {
|
|
if (s.find(1) == s.end()) { // Noncompliant
|
|
doSomething();
|
|
}
|
|
}
|
|
|
|
void f2(std::unordered_map<std::string, int> &m) {
|
|
if (m.count("key") != 0) { // Noncompliant
|
|
doSomething();
|
|
}
|
|
}
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,cpp,diff-id=1,diff-type=compliant]
|
|
----
|
|
void f1(std::set<int> &s) {
|
|
if (!s.contains(1)) { // Compliant
|
|
doSomething();
|
|
}
|
|
}
|
|
|
|
void f2(std::unordered_map<std::string, int> &m) {
|
|
if (m.contains("key")) { // Compliant
|
|
doSomething();
|
|
}
|
|
}
|
|
----
|
|
|