C++ 错误(将 wstring 转换为字符串):无法将参数 1 从 std::wchar_t 转换为 std::char

标签 c++ string similarity wstring

#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/

相关文章:

c++ - Visual Studio 2010 调试器指向错误的行

java - Java中的多行字符串连接

algorithm - 如何根据发音计算英语单词之间的相似度得分?

algorithm - 树之间的相似之处

c++ - ListView 控件不出现在对话框中

c++ - 当 select 子句中使用 case 时,Oracle 数字精度和小数位数均为零

c++ - Qt:QWidget::paintEngine:不应再调用

python - 在任意索引处有效地划分字符串

java - Java 中有效且漂亮的字符串条件

mysql - 根据mysql表中存储的数据创建相似度矩阵