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

时间:2015-01-13 07:57:33

标签: 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;
}

在上面的代码中,&#34; string1_bigrams.insert(string1.substr(i,2));&#34;和&#34; string1_bigrams.insert(string1.substr(i,2));&#34;不起作用。
我使用的是Visual Studio 2013 Ultimate。系统说&#34;无法转换为&#39; std :: basic_string,std :: allocator&gt;&#39; to&#39; std :: basic_string,std :: allocator&gt;&#39; 1 GT;没有可用于执行此转换的用户定义转换运算符,或者无法调用运算符&#34; 请告诉我如何解决它。谢谢。

2 个答案:

答案 0 :(得分:1)

最简单的解决方法是将set<string>转换为set<wstring>

set<wstring> string1_bigrams;
set<wstring> string2_bigrams;

.
.
.

for (set<wstring>::iterator IT = string2_bigrams.begin();

此外,您应该为主要功能返回int

请参阅demo

答案 1 :(得分:0)

如果您愿意,可以考虑使用std::set<wstring>作为M M.建议。

如果你出于任何原因不能......你可以使用它:

//string1_bigrams.insert(string1.substr(i, 2));
string1_bigrams.insert(&string1[i], &string1[2]);

此外,您应该考虑将函数参数作为参考传递,否则主函数中的硬编码构造字符串将被复制并传递给函数。

float dice_coefficient(std::wstring &string1, std::wstring &string2)