-3

I have a class that will provide a function with an item seen which will return false the first time it's seen with a certain string, but true every time after that when the same string is called.

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

2 に答える 2

2

It sounds like you need/want either an std::set<std::string> or an std::unordered_set<std::string>.

When you receive an item, attempt to insert it into the [unordered_]set. Check the return value to see if that succeeded or not.

Note that searching for the item first, then attempting to insert if it's not present is fairly wasteful. You normally just want to attempt to insert it, and then check the return value to see if that succeeded:

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

If you do a search and then insert, you're forcing it to search the collection twice when/if it inserts a new object. Using the return value instead allows you to do the search only once. IOW, you can expect it to be roughly twice as fast (though caching is likely to make the second search faster, so the measured difference may be smaller than that).

于 2013-02-06T02:57:34.080 に答える
2

Simplest way is by using 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;
}
于 2013-02-06T02:59:05.373 に答える