PointCloudLibrary / PointCloudLibrary/pcl

Checking for existence in `std::map` - `count` vs `find`

Open
#4,083 13 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

kind: question needs: feedback
Dominant language
C++
Stars
11.1k
Forks
4.7k
Avg merge
4d 10h
Merged PRs (30d)
6

Description

Currently we are using a lot of iterators just to check if an element exists in a map, like here:
https://github.com/PointCloudLibrary/pcl/blob/f9f214f34a38d5bb67441140703a681c5d299906/visualization/src/pcl_visualizer.cpp#L3261-L3268

To increase readability we have two options:
Option 1) Use auto

  auto am_it = cloud_actor_map_->find (id);
  if (am_it != cloud_actor_map_->end ())
  ...

Option 2) As single line:

  if (cloud_actor_map_->find (id) != cloud_actor_map_->end ())
  ...

Option 3) With count (complexity is logarithmic like find)

  if (cloud_actor_map_->count (id) > 0)
  ...

See similar discussion on StackOverflow.

Pro/Cons:

  • Option 1) iterator variable is longer valid as necessary
  • Option 2) In case of a long variable name we may reach the maximum line length defined by clang-format => line break
  • Option 3) Shortest and imho best to read, but performance maybe be a few CPU ticks slower (GCC should be equal, but MSVC not sure)

So prefer performance or readability?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at visualization/src/pcl_visualizer.cpp lines 3261-3268 and review the linked discussion of find versus count. Compare the proposed styles and their readability and performance trade-offs, then define the project-wide preference; done means the choice and its scope are agreed upon.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
developer-experience
Issue type
Refactor
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.