C++跟踪一个项目一次,然后返回

C++ tracking an item once and then returning

本文关键字:一次 返回 然后 一个 跟踪 C++ 项目      更新时间:2023-10-16

我有一个类,它将提供一个带有可见项的函数,该函数在第一次看到某个字符串时将返回false,但在那之后每次调用同一个字符串时都返回true

class Tracking
{
     ...
public:
     bool itemseen(const char* str)
     {
         ..
     }       
};

听起来您需要/想要std::set<std::string>std::unordered_set<std::string>

当您收到一个项目时,请尝试将其插入到[unordereded_]集合中。检查返回值,看看是否成功。

请注意,先搜索项目,然后在不存在的情况下尝试插入是相当浪费的。您通常只想尝试插入它,然后检查返回值,看看是否成功:

class whatever { 
    std::set<std::string> strings;
public:
    bool itemseen(std::string const &input) { 
       return !strings.insert(input).second;
    }
};

如果先进行搜索,然后插入,则在插入新对象时/如果插入新对象,则会强制它搜索集合两次。使用返回值可以只进行一次搜索。IOW,你可以预期它的速度大约是原来的两倍(尽管缓存可能会使第二次搜索更快,所以测量到的差异可能会更小)。

最简单的方法是使用STL:

#include <set>
#include <string>
std::set<std::string> seen;
bool itemseen(const char* str)
{
  if (seen.find(str) == seen.end())
  {
    seen.insert(str);
    return false;
  }
  return true;
}