如何检查是否存在具有相同前缀的双关键字
How to check whether there is a two key with the same prefix?
有这样的地图:
typedef std::string Path; // has this format "/<a>/<b>/<c>"
typedef std::vector<std::string> Paths;
typedef std::map<std::string, Paths> PathMapping;
PathMapping mathMapping; // ( "/a/b/c" --> "/a/b/c1", "a/b/c2" )
( "/a/b/d" --> "/a/b/d1", "a/b/d2" )
("/a/b/c/d" --> "a/b/c/d1", "a/b/c/d2" ) // not allowed
如何检查映射中是否有其他键的子字符串键?
map
中的密钥按字典顺序排序,因此,如果一个密钥A
将成为另一个密钥B
的前缀,则:
A
在B
之前A
也是A
和B
之间的任何密钥的前缀
因此,我们可以在地图中进行简单的扫描(此处为m
):
auto current = m.begin();
for (auto it = next(current), end = m.end(); it != end; ++it ) {
// Note: if current is not a prefix of "it", then it cannot be a prefix
// of any key that comes after "it", however of course "it" could
// be such a prefix.
// current is not a prefix of "it" if "it" is shorter
if (it->first.size() <= current->first.size()) { current = it; continue; }
// current is not a prefix of "it"
if (it->first.substr(0, current->first.size()) != current->first) {
current = it; continue;
}
// current is a prefix
std::cout << "'" << current->first << "' is a prefix of '" << it->first << "'n";
}
注意:计算子字符串是不必要的,不分配的starts_with
函数会更好,但它确实能理解这一点
你可以在这里查看完整的代码。
不更改数据结构:
for (const auto& p : mathMapping)
for (const auto& s : mathMapping)
if (starts_with(p.first, s.first))
// collision
它的C++03版本是:
for (PathMapping::const_iterator p = mathMapping.begin(); p != mathMapping.end(); ++p)
for (PathMapping::const_iterator s = mathMapping.begin(); s != mathMapping.end(); ++s)
if (starts_with(p->first, s->first))
// collision
其中CCD_ 11是这里提出的函数之一。
但如果您可以更改数据结构,我会用/
分割每个段,并使用树状容器。
相关文章:
- Visual Studio 2015:Extern "C" 和 "export" 关键字
- C++中的"inline"关键字
- 如何确保C++函数在定义之前声明(如override关键字)
- 谷歌模拟和覆盖关键字
- 结构体 S { int align; } 之间的区别;(struct 关键字后的名称)和 struct { int al
- 如果全局变量默认是外部变量,为什么要添加"extern"关键字?
- 编译器如何在前缀和 postix 运算符之间进行区分?
- 当我从下面的代码中删除关键字 virtual 时,它可以正常工作,否则会出现错误。在这里"virtual"字的意义是什么?
- 为什么"delete"关键字不删除节点?
- 在 c++ 中正确定义"this"关键字?
- 这个额外的关键字在这个 c++ 类声明中是什么意思?
- 在 typedef 内部使用 const 关键字和在 typedef 外部使用 const 关键字之间有区别吗?
- 查找带有 Anaconda cmake 前缀的 boost-python3
- C++ - 为什么这里需要'template'关键字?
- C++函数的关键字?
- 迭代器类的重载前缀增量运算符会引发分段错误
- 使用 'typename' 关键字将非类型视为依赖上下文中的类型
- 代码 C++ 以添加前缀关键字以使其有效
- 构造函数定义是否可以以 "class" 关键字为前缀?
- 如何检查是否存在具有相同前缀的双关键字