Tak*_*ndo 2 c++ dictionary insert rust
我正在将 C++ 代码传输到 Rust。这是原始的 C++ 代码。
#include <map>
#include <string>
#include <cassert>
#include <iostream>
int main() {
std::map<std::string, int> m {
{ "A", 1 },
{ "B", 2 },
{ "D", 4 },
};
// *1
auto r = m.equal_range("C"); // *2
if (r.first == r.second) {
auto const& it = r.first;
assert(it->first == "D");
assert(it->second == 4);
// Let's say creating the object to insert is high cost
// so it should be created only if the element doesn't exist.
// Creating the object at *1 is not acceptable because if the element exists,
// then the created object isn't userd.
//
// `it` is hint iterator that point to insertion position.
// If the object to isnert has the same key as the argument of equal_range (*2)
// the time complexity is O(1).
m.emplace_hint(it, "C", 3);
}
for (auto const& kv : m) {
std::cout << kv.first << ":" << kv.second << std::endl;
}
}
Run Code Online (Sandbox Code Playgroud)
可运行演示:https://wandbox.org/permlink/4eEZ2jY9kaOK9ru0
这是插入如果不存在模式。
我想实现两个目标。
一是有效地插入对象。搜索对象需要 O(logN) 时间复杂度。我只想在地图中不存在该对象时插入新对象。如果从头开始插入新对象,则需要 O(logN) 额外成本来搜索插入位置。原始 C++ 代码用作it
插入新对象的提示。
另一种是仅当映射中不存在具有相同键的对象时才创建新对象。因为在实际情况下创建对象需要很高的成本。(我的示例代码使用 std::string 和 int 值。这只是一个示例。)因此,我不想预先创建用于在 *1 处插入的对象。
我阅读了 BTreeMap 文档。但我找不到路。
https://doc.rust-lang.org/std/collections/struct.BTreeMap.html
有什么好的办法吗?或者是否有任何非标准容器(地图)来支持我想做的操作?
看起来您想要 Entry API?
在您的示例的 rustification 中,m.entry("C")
将返回一个Entry枚举,其中包含条目是否存在的信息。然后,您可以显式分派或使用高级方法之一,例如,BTreeMap::or_insert_with
它接受一个函数(从而创建要延迟插入的对象)
所以 Rust 版本将是这样的:
let mut m = BTreeMap::new();
m.insert("A", 1);
m.insert("B", 2);
m.insert("D", 4);
m.entry("C").or_insert_with(|| {
3 // create expensive object here
});
for (k, v) in &m {
println!("{}:{}", k, v);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2047 次 |
最近记录: |