我一直在用C++写一个回文查找器,我已经成功地编写了一个......至少可以说是基本的.
我只想增加程序的速度,现在需要大约1m 5s才能使用我拥有的功能在1500字的单词列表上运行palindromes/2字回文测试.我想尝试在更大的文件上运行它,但却看不到我可以进一步优化的位置?
任何帮助将不胜感激:PS这不是为了学校,只是为了休闲.
#include <iostream>
#include <ostream>
#include <vector>
#include <fstream>
#include <algorithm>
using namespace std;
bool isPal(string);
int main() {
vector<string> sVec;
vector<string> sWords;
vector<string> sTwoWords1;
vector<string> sTwoWords2;
char myfile[256]="/home/Damien/Test.txt";
ifstream fin;
string str;
fin.open(myfile);
if(!fin){
cout << "fin failed";
return 0;
}
while(fin){
fin >> str;
sWords.push_back(str);
if(!fin){
break;
}
if(isPal(str)){
sVec.push_back(str);
}
else{
getline(fin, str);
}
}
reverse(sVec.begin(), sVec.end());
for(int i =0; i < sVec.size(); i++){
cout << sVec[i] << " is a Palindrome " <<endl;
}
// Test 2
for(int i=0; i<sWords.size(); i++){
for(int j=(i+1); j<sWords.size(); j++){
str = sWords[i]+sWords[j];
if(isPal(str)){
sTwoWords1.push_back(sWords[i]);
sTwoWords2.push_back(sWords[j]);
}
}
}
fin.close();
for(int i=0; i<sTwoWords1.size(); i++){
cout << sTwoWords1[i] << " and " << sTwoWords2[i] << " are palindromic. \n";
}
return 0;
}
bool isPal(string& testing) {
return std::equal(testing.begin(), testing.begin() + testing.size() / 2, testing.rbegin());
}
Run Code Online (Sandbox Code Playgroud)
你做了很多不必要的工作来测试它是否是回文.只需使用std::equal:
#include <algorithm>
bool isPal(const string& testing) {
return std::equal(testing.begin(), testing.begin() + testing.size() / 2, testing.rbegin());
}
Run Code Online (Sandbox Code Playgroud)
这将从字符串的开头到字符串的中间,从字符串的末尾到中间进行迭代,然后比较字符.我不记得是谁给我这个,但我没想到.
编辑:我在另一个关于回文的问题中从Cubbi学到了这一点.