过载C++插入
是否可以在字符串集中重载compare运算符,使其定义两个编辑距离的元素,但由于以下两个原因无法编译: 递归调用min函数,但参数太少 getEditDist和operator的参数必须是常量 除此之外,getEditDist中的递归永远不会完成 即,这将编译:过载C++插入,c++,set,operators,overloading,C++,Set,Operators,Overloading,是否可以在字符串集中重载compare运算符,使其定义两个编辑距离的元素,但由于以下两个原因无法编译: 递归调用min函数,但参数太少 getEditDist和operator的参数必须是常量 除此之外,getEditDist中的递归永远不会完成 即,这将编译: #include <string> #include <set> #include <vector> #include <iostream> #include <algorithm&
#include <string>
#include <set>
#include <vector>
#include <iostream>
#include <algorithm>
int min3(int x, int y, int z)
{
return std::min(std::min(x, y), z);
// Or just use `std::min({x, y, z})` if you have C++11 available
}
int getEditDist(const std::string& str1, const std::string& str2, int m, int n)
{
if (str1[m-1] == str2[n-1])
return getEditDist(str1, str2, m-1, n-1);
return 1 + min3(
getEditDist(str1, str2, m, n-1),
getEditDist(str1, str2, m-1, n),
getEditDist(str1, str2, m-1, n-1));
}
class editDist
{
public:
bool operator () (const std::string& str1, const std::string& str2)
{
return(getEditDist(str1, str2, str1.length(), str2.length()) <= 1);
}
};
int main(int argc, char* argv[])
{
std::string id1 = "AAA";
std::string id2 = "BBB";
std::string id3 = "BAB";
std::set<std::string, editDist> my_set;
//set<string> my_set;
std::set<std::string, editDist>::const_iterator itr;
//set<string>::const_iterator itr;
my_set.insert(id1);
my_set.insert(id2);
my_set.insert(id3);
for(itr = my_set.begin(); itr != my_set.end(); ++itr)
std::cout << *itr<< std::endl;
return 0;
}
但当您运行它时,它会导致堆栈溢出。你需要
更改getEditDist使其停止。TLDR:不,不可能执行您想要的操作 详情: 您可以定义一个比较器,其中da,b≤ 1.⇒ A.∼ b 唯一有效的比较器是∀a、 b,a∼ b这是非常无用的 然而,不可能定义da、b≤ 1.⇔ A.∼ b这才是你真正想要的 比较器定义字符串的顺序和等价类。如果需要任意两个具有编辑距离的图元≤ 1在同一等价类中,这意味着具有编辑距离的任何元素≤ 2也在相同的等价类中。我们可以继续对任何可能的编辑距离进行推理,因此所有字符串必须处于相同的等价类中:
struct always_equal_less {
bool operator()(std::string const& x, std::string const& y) const {
return false;
}
};
更正式的解释
的比较参数必须遵循这个概念,即它必须定义严格的弱序关系。它必须具有以下属性:
及物性≺ B∧ B≺ C⇒ A.≺ c
不可逆性≺ a
非对称性≺ B⇒ -b≺ a
不可比性的及物性∼ B∧ B∼ C⇒ A.∼ c
我用的是一个∼ b代表a≺ B∧ -b≺ a
让我们假设我们有这样的关系≺ 它还有一个附加属性,即对于编辑距离小于或等于1的任意两个元素,都等于:da,b≤ 1.⇒ A.∼ b
我们可以证明,唯一符合此条件的关系将所有字符串作为相等项进行比较:∀a、 b,a∼ b:
让我们选取编辑距离为2,da,b=2的两个元素。我们可以找到第三个元素c,比如:da,c=1和dc,b=1。我们有一个∼ c和c∼ B不可比性的及物性给出了:a∼ B这意味着编辑距离为2的任意两个图元也被视为相等:∀a、 b,da,b=2,a~b
可以继续对dx,y=3,dx,y=4进行推理。这表明任何给定的字符串对都必须进行相等的比较
我们得到了无用的关系∀a、 b,a~b
因此,不可能定义da,b≤ 1.⇔ A.∼ b、 如果它没有编译,那么肯定没有正确编码。具体错误是什么?请注意使用namespace std;。您可能会发现自己调用std::min而不是min.Stack overflow,只有当程序在m或n变为负值时,才会调用它。很好的解释。有人没有逃过代数课。
struct always_equal_less {
bool operator()(std::string const& x, std::string const& y) const {
return false;
}
};