C++ C+中的字谜解算器+;
我正在为学校做一个项目,我被困在我认为只是一小部分的事情上,但我无法理解 以下是我到目前为止的情况:C++ C+中的字谜解算器+;,c++,find,anagram,C++,Find,Anagram,我正在为学校做一个项目,我被困在我认为只是一小部分的事情上,但我无法理解 以下是我到目前为止的情况: #include <iostream> #include <fstream> #include <string> #include <locale> #include <vector> #include <algorithm> #include <set> using namespace std; int m
#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;
}
如果你们能帮我或给我指出正确的方向,我将不胜感激。我想你们需要写这样的东西:
for (unsigned int i = 0; i < str.size(); i++)
if (setwords.find(str[i]) != setwords.end())
cout << str[i] << endl;
if (*(setwords.find(word)) == str[i])
for(无符号整数i=0;i 首先,我想说这是一个问得很好的问题。我感谢新用户花时间详细阐述他们的问题
问题是std::set
的find()
方法返回一个迭代器对象,该对象指向它找到的值,如果不能返回,则返回容器的end()
。当您将它与str[i]
(字符串)进行比较时,它找不到同时使用迭代器和字符串的operator==()
的合适重载
您可以将返回值与end()
进行比较,以确定它是否找到字符串,而不是与字符串进行完全比较:
if(setwords.find(str[i])!=setwords.end()
// ^^^^^^ ^^^^^^^^^^^^^^
如果表达式返回true
,则它成功地在集合中找到字符串
我还想在您的代码中解决另一个潜在问题。使用if(!file.eof())
来调节输入是错误的。您应该将提取部分作为条件,如下所示:
for (unsigned int i = 0; i < str.size(); i++)
if (setwords.find(str[i]) != setwords.end())
cout << str[i] << endl;
if (*(setwords.find(word)) == str[i])
用于(std::string项;infle>>项;)
{
插入(项目);
}
下面是另一种方法,使用std::istream\u迭代器
:
setwords.insert(std::istream_迭代器(infle),
std::istreamu迭代器();
事实上,你已经非常接近正确了
如果在集合中找到值,则set::find
方法不会返回该值,而是返回。因此,if
语句将当前字符串与返回的迭代器对象(而不是迭代器指向的值)进行比较
要获得迭代器指向的值,只需像指针一样取消引用它,在它前面加一个星号。这意味着您可能希望您的语句如下所示:
for (unsigned int i = 0; i < str.size(); i++)
if (setwords.find(str[i]) != setwords.end())
cout << str[i] << endl;
if (*(setwords.find(word)) == str[i])
这适用于在集合中找到值的情况,但在未找到值的情况下会有问题。如果找不到该值,则返回一个迭代器,该迭代器指向集合中最后一项之后的位置,并且您不应该尝试取消引用此类迭代器(因为它不指向有效对象)
通常执行这些检查的方法是将返回的迭代器与指向集合末尾的迭代器进行比较(例如,在本例中为set::end)。如果迭代器不匹配,则表示找到了该项
if (setwords.find(word) != setwords.end())
cout << word << endl;
if(setwords.find(word)!=setwords.end())
cout+1,感谢您做出努力,并将您遇到的问题张贴到哪里,而不仅仅是要求我们为您编写代码。这变得不寻常了。