问题描述
我一直在用C ++编写一个回文查找器,我已经成功地编写了一个基本的,至少可以说。
I have been writing a palindrome finder in C++ and I have succeeded in writing one that is.... basic to say the least.
以增加程序的运行速度,现在它需要大约1m 5s运行一个测试回文/ 2字回文在1500字wordlist使用我有的功能。我想尝试在一个更大的文件上运行它,但没有看到我可以进一步优化。
I am looking simply to increase the runspeed of the program, right now it takes about ~1m 5s to run a test for palindromes / 2 word palindromes on a 1500 word wordlist using the functions that I have. I would like to try running it on a much larger file but fail to see where I can optimize further?
任何帮助将不胜感激。这不是为了学校,只是为了休闲。
Any help would be appreciated: P.S. This is not for school, just for leisure.
#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());
}
推荐答案
的不必要的工作来测试它是否是回文。只需使用 std :: equal
:
You're doing a lot of unnecessary work to test if it is a palindrome. Just use std::equal
:
#include <algorithm>
bool isPal(const string& testing) {
return std::equal(testing.begin(), testing.begin() + testing.size() / 2, testing.rbegin());
}
这将从字符串的开头重复到中间和结束的字符串到中间,并比较字符,因为它。我不记得谁给了我这个,但我没有想到它。
This will iterate from the beginning of the string to the middle and from the end of the string to the middle and compare the characters as it goes. I can't remember who showed me this, but I didn't think of it.
编辑:我从Cubbi在。
I learned it from Cubbi in another question about palindromes.
这篇关于C ++ Palindrome finder优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!