словарь — программа поиска анаграмм в Stack Overflow

Мне нужно код программы, которая находит анаграммы слов. Когда программа запускается, она просит пользователя ввести слова в «словарь», который впоследствии будет искать анаграммы слов, которые снова будет вводить пользователь.

Я сохранил все слова словаря в векторе oldDict, Символы в каждом слове затем располагаются в алфавитном порядке, а новые отсортированные символы сохраняются в векторе, называемом newDict, чтобы сохранить оригинальные слова в oldDict,

Затем пользователь вводит слово, для которого анаграмма (ы) должна быть найдена в словаре. как только слово введено, я снова попытался отсортировать символы слова по алфавиту, чтобы затем сравнить его с каждым элементом в newDict и найти анаграммы таким образом.

Ниже мой код:

ifndef ANAGRAM_H
#define ANAGRAM_H
#include <iostream>
#include <vector>
#include <string>
using namespace std;

vector <string> oldDict;
vector <string> newDict;
int dictSize = 0;

void readDict(void){    // Allows the user to input all the words they would like to     have in the anagram dictionary.
cout<< "Please enter the number of dictionary entries you wish to create\n";
cin >> dictSize;
string word = "";
cout << "Please enter the dictionary entries, 1 by 1, pushing <enter> after each entry.\n";
for(int i = 0; i <dictSize; i++){
cin >> word;
oldDict.push_back(word);
}
newDict = oldDict;
}

void sortChars(void){   //sorts the letters in each word of the 'dictionary' so that the     letters are in alphabetical order.
for(int i = 0; i < dictSize; i++){
std::sort(newDict[i].begin(), newDict[i].end());
}
}

void getWords(void){
int num = 0;
cout << "Please enter the number of words for which you would like to find anagrams     of:\n";
cin >> num;
string word = "";
for(int i = 0; i < num; i ++){
cout << "Please enter a word:\n";
cin>>word;
std::sort(word.begin(), word.end());
for(int i = 0; i < dictSize; i++){
string word2 = newDict[i];
bool isAn = isAnagram(word, word2);
if(isAn == true){
cout << oldDict[i];
} else{
}
}
}
}

bool isAnagram(string word1, string word2){

if(word1.compare(word2) ==0){
return true;
} else {
return false;
}
}

void menu(void){
readDict();
sortChars();
getWords();
}
#endif

Процесс начинается в order() функция в нижней части кода.

При попытке скомпилировать код я получаю следующие ошибки:

In file included from main.cpp:3:0:
./anagram.h: In function ‘void sortChars()’:
./anagram.h:25:3: error: ‘sort’ is not a member of ‘std’
std::sort(newDict[i].begin(), newDict[i].end());
^
./anagram.h: In function ‘void getWords()’:
./anagram.h:37:4: error: ‘sort’ is not a member of ‘std’
std::sort(word.begin(), word.end());
^
./anagram.h:40:38: error: ‘isAnagram’ was not declared in this scope
bool isAn = isAnagram(word, word2);

Может ли кто-нибудь помочь мне решить эти ошибки? Я действительно не понимаю, пока «isAnagram» выдает ошибку, а также, если кто-нибудь может объяснить, что делает «std ::» и почему эти две строки кода вызывают ошибки?

Спасибо большое

0

Решение

‘sort’ is not a member of ‘std’ добавлять #include <algorithm>

‘isAnagram’ was not declared in this scope Объявите функцию перед ее первым использованием.

Более того, реализация isAnagram выглядит неправильно. Вы не можете просто сравнить строки. Вы должны отсортировать строки перед их сравнением.

bool isAnagram(string word1, string word2){
std::sort(word1.begin(), word1.end()); // added
std::sort(word2.begin(), word2.end()); // added
if(word1.compare(word2) ==0){
return true;
} else {
return false;
}
}
1

Другие решения