#include <stdio.h>
#include <iostream>
#include <cstring>
#include <math.h>
#include <iterator>
#include <set>
#include <string>
#include <Windows.h>
using namespace std;
/*
* dice coefficient = bigram overlap * 2 / bigrams in a + bigrams in b
* (C) 2007 Francis Tyers
* Modifications made by Stefan Koshiw 2010
* Now it outputs values [0..1]
* Released under the terms of the GNU GPL.
*/
float dice_coefficient(wstring string1, wstring string2);
void main()
{
float dice = 0;
wstring str1(L"save");
wstring str2(L"gave");
dice = dice_coefficient(str1, str2);
cout << dice;
}
float dice_coefficient(wstring string1, wstring string2)
{
set<string> string1_bigrams;
set<string> string2_bigrams;
//base case
if (string1.length() == 0 || string2.length() == 0)
{
return 0;
}
for (unsigned int i = 0; i < (string1.length() - 1); i++) { // extract character bigrams from string1
string1_bigrams.insert(string1.substr(i, 2));
}
for (unsigned int i = 0; i < (string2.length() - 1); i++) { // extract character bigrams from string2
string2_bigrams.insert(string2.substr(i, 2));
}
int intersection = 0;
// find the intersection between the two sets
for (set<string>::iterator IT = string2_bigrams.begin();
IT != string2_bigrams.end();
IT++)
{
intersection += string1_bigrams.count((*IT));
}
// calculate dice coefficient
int total = string1_bigrams.size() + string2_bigrams.size();
float dice = (float)(intersection * 2) / (float)total;
return dice;
}
在上面的代码中,“string1_bigrams.insert(string1.substr(i, 2));”和“string1_bigrams.insert(string1.substr(i, 2));”不起作用。
我使用的是 Visual Studio 2013 Ultimate。系统说“无法从‘std::basic_string,std::allocator>’转换为‘std::basic_string,std::allocator>’
1> 没有可用的可以执行此转换的用户定义转换运算符,或者无法调用该运算符”
请告诉我如何解决它。谢谢。
最佳答案
最简单的解决方法是转换 set<string>
至 set<wstring>
:
set<wstring> string1_bigrams;
set<wstring> string2_bigrams;
.
.
.
for (set<wstring>::iterator IT = string2_bigrams.begin();
此外,您应该返回 int
用于主要功能。
参见 demo .
关于C++ 错误(将 wstring 转换为字符串):无法将参数 1 从 std::wchar_t 转换为 std::char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27917328/