Why is this an issue?
Using a size()
, length()
or count()
method to test for emptiness works, but using an empty()
or
is_empty()
method makes the code more readable and can be more performant. The time complexity of any
empty()
/is_empty()
method implementation should be O(1)
, whereas some implementations of size()
,
length()
or count()
can be O(n)
.
Noncompliant code example
void fun(const std::vector<int> &myVector) {
if (myVector.size() == 0) { // Noncompliant
// do something
}
}
Compliant solution
void fun(const std::vector<int> &myVector) {
if (myVector.empty()) {
// do something
}
}
Resources