我正在将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;
}
}
可运行的演示: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?
在示例中,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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句