【发布时间】:2013-09-20 23:07:41
【问题描述】:
我正在开发一个程序,该程序使用std:count 查看特定单词是否为字谜,但我认为我的函数逻辑不正确,我似乎无法弄清楚。
假设文件中有以下单词:
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 感谢您的回复。但是要我确定 Anagram,我需要能够访问 str[i...n] 的元素,对吧?
-
你能澄清一下吗?您是否试图找出文件中的每个单词是否在同一个文件中有另一个单词是它的字谜?你能提供预期的输出吗?
-
@masahji 所以这里的预期输出是:3 因为文本文件中的每个单词都是单词“Evil”的变位词
-
@PHorce 感谢您的澄清。您的文件实际上有 4 行(每行都是“Evil”的字谜,作为参数传递给
Compare)。那么它不会输出 4 吗?
标签: c++ string algorithm logic