C++跟踪一个项目一次,然后返回
C++ tracking an item once and then returning
我有一个类,它将提供一个带有可见项的函数,该函数在第一次看到某个字符串时将返回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;
}
相关文章:
- 我是否需要在下一次转移时将所有权*转移回转移队列
- 使用仅使用一次的变量调用的复制构造函数.这可能是通过调用move构造函数进行编译器优化的情况吗
- 在C++中一次将矢量值写入多个文件
- 循环中的条件:为什么每次都调用strlen(),而vector.size()只调用一次
- 为什么 zlib 放气初始化调用一次不起作用?
- 在一次迭代中从 txt 文件中读取多行
- 为什么无论你输入什么,这"while(cin.get(str,3))"只运行一次?
- 从子菜单返回后,正确的输入至少进入验证循环一次
- 如何在返回一次数据后从类实例中删除数据
- 递归:一次返回
- C++不止一次返回
- 如何使用C++单一实例返回仅初始化一次的对象
- C++重载getter两次,一次返回指针,另一次返回常量引用,都失败了
- 如何在c++中一次又一次地从函数返回
- 如何使用数据类型的一次返回来返回错误
- 如何写函数整洁?考虑到log,一次返回,不再缩进
- 为什么popn()一次又一次调用返回相同的输出
- Std::istringstream.good()比预期多返回一次true
- "Peek ahead"检查下一次对getline(file,line)的调用是否会返回false - 而不实际调用它,即不消耗该行
- C++跟踪一个项目一次,然后返回