gpt4 book ai didi

c++ - C++ 中的 Anagram 求解器

转载 作者:太空狗 更新时间:2023-10-29 23:04:30 26 4
gpt4 key购买 nike

我正在为学校做一个项目,我被困在我认为只是一小部分但我无法弄清楚的地方。

这是我目前所拥有的:

#include <iostream>
#include <fstream>
#include <string>
#include <locale>
#include <vector>
#include <algorithm>
#include <set>

using namespace std;

int main(int argc, char* argv[])
{
set<string> setwords;
ifstream infile;
infile.open("words.txt"); //reads file "words.txt"
string word = argv[1]; // input from command line
transform(word.begin(), word.end(), word.begin(), tolower); // transforms word to lower case.
sort(word.begin(), word.end()); // sorts the word
vector<string> str; // vector to hold all variations of the word

do {
str.push_back(word);
}
while (next_permutation(word.begin(), word.end())); // pushes all permutations of "word" to vector str

if (!infile.eof())
{
string items;
infile >> items;
setwords.insert(items); //stores set of words from file
}

system("PAUSE");
return 0;
}

现在我需要比较文件中的单词和存储在 vector str 中的排列并打印出真正的单词。

我知道我需要使用set类的find方法。我只是不知道该怎么做。我正在尝试这样的事情但没有运气,但我的思考过程可能是错误的。

for (unsigned int i = 0; i < str.size(); i++)
if (setwords.find(word) == str[i])
cout << str[i] << endl;

如果你们能帮助我或指出正确的方向,我将不胜感激。

最佳答案

首先,我想说这是一个很好的问题。感谢新用户花时间详细说明他们的问题。

问题是 find() std::set<> 的方法返回指向它找到的值的迭代器对象,或 end()如果不能的话,容器的。当您将它与 str[i] 进行比较时(一个字符串)找不到合适的重载 operator==()它同时接受迭代器和字符串。

您可以将返回值与 end() 进行比较,而不是与字符串进行全面比较。确定它是否找到了字符串:

if (setwords.find(str[i]) != setwords.end())
// ^^^^^^ ^^^^^^^^^^^^^^

如果表达式返回 true , 然后它成功地找到了集合中的字符串。

我还想在您的代码中解决另一个潜在问题。使用 if (!file.eof())是条件输入的错误方法。您应该改为将提取部分作为条件的一部分,如下所示:

for (std::string item; infile >> item; )
{
setwords.insert(item);
}

这是另一种方式,使用 std::istream_iterator<> :

setwords.insert(std::istream_iterator<std::string>(infile),
std::istream_iterator<std::string>());

关于c++ - C++ 中的 Anagram 求解器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22738219/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com