#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
string buildRWord(string word) {
string rword = "";
vector<string> wrd;
for(int i = 0; i < word.length(); ++i)
wrd.push_back(word.substr(i,1));
reverse(word.begin(), word.end());
for(int i = 0; i < word.size(); ++i)
rword += word[i];
return rword;
}
int main()
{
string aword;
cout << "Enter a word: ";
cin >> aword;
string raword = buildRWord(aword);
if (raword == aword)
cout << aword << " is a palindrome."
<< endl;
else
cout << aword << " is not a palindrome."
<< endl;
return 0;
}
这个程序运作完美,但我不知道它是如何工作的我是指内部的逐步操作。有人可以解释这段代码吗?我需要有关全局功能部分的详细说明。
答案 0 :(得分:0)
它检查给定的字符串是否是回文。视图只是具有动态大小附加功能的数组。这里在String上调用reverse(),参数指定字符串的开头和字符串的结尾,反向函数反转范围[first,last]中元素的顺序。程序正在使用它,你也可以使用矢量wrd。如果您不打算使用它,您可以考虑删除有关向量的那些行。
#include <iostream>
#include <vector>
#include <algorithm>
/* On top you have added all the library functions, vector data structure is like array but its size can dynamically change, iostream allows you to accept input from user, alogorithm avails all the other necessary algorithmic functions for the purpose.
*/
using namespace std;
string buildRWord(string word) {// The variable word gets aword in the call in the main function
string rword = "";
vector<string> wrd;// Declaring a vector variable
for(int i = 0; i < word.length(); ++i)
wrd.push_back(word.substr(i,1));//pushing each character at the end of the vector using call to push_back, push_back always puts a new element at the end of the vector
reverse(word.begin(), word.end());// reverse the word
for(int i = 0; i < word.size(); ++i)// adding the characters from word to rword, one at a time.
rword += word[i];
return rword;// returning rword
}
int main()
{
string aword;
cout << "Enter a word: ";
cin >> aword;// Storing the input word in this String called aword
string raword = buildRWord(aword);// Calling the function buildRWord on aWord
if (raword == aword)// Checking for string equality
cout << aword << " is a palindrome."// if equal is a palindrome.
<< endl;
else
cout << aword << " is not a palindrome."// if not equal is not a palindrome.
<< endl;
return 0;
}