相关疑难解决方法(0)

如何使用不同类型的键搜索std :: map

如果我有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,原则上我应该能够在我的地图中找到匹配的项目,因为我可以得到一个idsubId一对.但我能做到这一点,而无需创建的实例X在和复制idsubId

c++ performance dictionary stl comparator

11
推荐指数
1
解决办法
1511
查看次数

C++ unordered_map&lt;string, ...&gt; lookup without constructing string

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, …

c++ string unordered-map c++11

5
推荐指数
1
解决办法
971
查看次数

当转发参数时,std :: move在参数列表中是否安全,而不是移动构造?

试图提供解决方案的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)

c++ move-semantics string-view c++17

5
推荐指数
1
解决办法
311
查看次数

在无序映射中使用 string_view 作为键的安全方法

我的类型 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++ c++17

5
推荐指数
1
解决办法
4633
查看次数