如果我有std::map<X, Blah>,使用实例查找地图中匹配项目的最佳方法是Y什么?
假设信息Y足以唯一地找到X,但出于性能原因,我不想X通过复制Y值来创建实例.
我知道我可以创建一个公共基类或接口做到这一点X,并Y和制作该地图的关键,但有没有其他办法?例如,创建某种比较对象?
以下是示例代码:
class X
{
public:
int id;
int subId;
};
std::map<X, Details> detailsMap;
class Y
{
public:
int getId();
int getSubId();
int someOtherUnrelatedThings1;
int someOtherUnrelatedThings2;
};
Run Code Online (Sandbox Code Playgroud)
现在,如果我有一个实例Y,原则上我应该能够在我的地图中找到匹配的项目,因为我可以得到一个id和subId一对.但我能做到这一点,而无需创建的实例X在和复制id和subId?
I have C++ code that investigates a BIG string and matches lots of substrings. As much as possible, I avoid constructing std::strings, by encoding substrings like this:
char* buffer, size_t bufferSize
Run Code Online (Sandbox Code Playgroud)
At some point, however, I'd like to look up a substring in one of these:
std::unordered_map<std::string, Info> stringToInfo = {...
Run Code Online (Sandbox Code Playgroud)
So, to do that, I go:
stringToInfo.find(std::string(buffer, bufferSize))
Run Code Online (Sandbox Code Playgroud)
That constructs a std::string for the sole purpose of the lookup.
I feel like there's an optimization I could do here, …
试图提供解决方案的std ::性病string_view和的std :: string :: unordered_set,我与更换玩弄std::unordered_set<std::string>与std::unordered_map<std::string_view, std::unique_ptr<std::string>>(该值std::unique_ptr<std::string>,因为小串的优化将意味着该地址string的底层数据并不总是被转移std::move.
我的原始测试代码似乎有用(省略标题):
using namespace std::literals;
int main(int argc, char **argv) {
std::unordered_map<std::string_view, std::unique_ptr<std::string>> mymap;
for (int i = 1; i < argc; ++i) {
auto to_insert = std::make_unique<std::string>(argv[i]);
mymap.try_emplace(*to_insert, std::move(to_insert));
}
for (auto&& entry : mymap) {
std::cout << entry.first << ": " << entry.second << std::endl;
}
std::cout << std::boolalpha << "\"this\" in map? " << (mymap.count("this") == 1) << std::endl; …Run Code Online (Sandbox Code Playgroud) 我的类型 Val 包含 std::string thekey。
struct Val
{
std::string thekey;
float somedata;
}
Run Code Online (Sandbox Code Playgroud)
我想将我的类型放入无序映射中,以 key 作为键。出于内存和避免转换的原因,我希望将 std::string_view 作为键类型。使用 unique_ptr 时是否可以创建指向 val.thekey 的密钥?
std::unique_ptr<Val> valptr = ...;
std::unordered_map<std::string_view,std::unique_ptr<Val>> themap;
themap[std::string_view(valptr->thekey)] = std::move(valptr); // is this ok and safe?
Run Code Online (Sandbox Code Playgroud) c++ ×4
c++17 ×2
c++11 ×1
comparator ×1
dictionary ×1
performance ×1
stl ×1
string ×1
string-view ×1