Я работаю над программой, которая смотрит, является ли конкретное слово анаграммой, используя std:count
, однако я не думаю, что моя функциональная логика правильная, и я не могу понять ее.C++ Поиск анаграмм в словах
Предположим, есть следующие слова в файле:
Evil
Vile
Veil
Live
Мой код выглядит следующим образом:
#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;
}
Я уверен, что это просто случай моей логики неправильно в функции. Надеюсь, кто-то может помочь :)
Для этой цели вам не нужен класс компаратора для 'std :: string', для этой цели он перегружает' operator =='. – jrok
@jrok Спасибо за ответ. Но для меня, чтобы определить Anagram, мне нужно иметь доступ к элементу str [i ... n], правильно? – Phorce
Не могли бы вы прояснить ситуацию. Вы пытаетесь выяснить каждое слово в файле, если оно содержит другое слово в том же файле, что и его анаграмма? Можете ли вы представить, каков ожидаемый результат? – masahji