C ++查找字谜文字字谜、文字

2023-09-11 23:24:12 作者:持刀人。

我工作的一个程序,看是否有特定的词是使用 STD字谜:计数不过,我不认为我的功能逻辑改正,我似乎无法弄清楚。

I'm working on a program that looks at whether or not a particular word is an anagram using std:count however, I don't think my function logic is correct and I cannot seem to figure it out.

假设有在文件中的以下文字:

Assume there are the following words in the file:

Evil
Vile
Veil  
Live

我的code是如下:

My code is as follows:

#include <iostream>
#include <vector>
#include <fstream>
#include <map>
using namespace std;

struct Compare {
std::string str;
Compare(const std::string& str) : str(str) {}
};

bool operator==(const std::pair<int, std::string>&p, const Compare& c) {
return c.str == p.second;
}
   bool operator==(const Compare& c, const std::pair<int, std::string>&p) {
   return c.str == p.second;
}

std::vector<std::string> readInput(ifstream& file)
{
std::vector<std::string> temp;

string word;

while (file >> word)
{
    temp.push_back(word);
}
std::sort(temp.begin(), temp.end());

return temp;
}

int main(int argc, char *argv[]) {  

string file = "testing.txt";
ifstream ss(file.c_str());

if(!ss.is_open())
{
    cerr << "Cannot open the text file";
}

std::vector<std::string> words = readInput(ss);

std::map<int, std::string> wordsMap; 

//std::map<std::string value, int key> values; 

for(unsigned i=0; (i < words.size()); i++)
{
    wordsMap[i] = words[i];
}


int count = std::count(wordsMap.begin(), wordsMap.end(), Compare("Evil"));
cout << count << endl;
}

我是pretty的肯定这只是我的逻辑的情况下是错误的功能。我希望有人能够帮助:)

I'm pretty sure it's just a case of my logic is wrong in the functions. I hope someone can help :)

推荐答案

最简单的方法是

要检查类似下面的(伪code)

To check like following (pseudo code)

布尔isAnagram(字符串s,串T){返回排序(S)==排序(T); }

所以,使用一些认为像以下,不需的std ::地图

So, use some think like following, no need of std::map

struct Compare {
std::string str;
Compare(const std::string& x) : str(x) { 
    std::sort(str.begin(),str.end()); std::transform(str.begin(), 
    str.end(),str.begin(), ::toupper);}

    bool operator ()(const std::string& t)
    {
        std::string s= t;
        std::transform(s.begin(), s.end(),s.begin(), ::toupper);
        std::sort(s.begin(),s.end());

    return s == str;
    }
};

然后

诠释计数=的std :: count_if(words.begin(),words.end(),比较(邪恶));

请参阅 这里

See HERE