【问题标题】:Can someone explain this c++ program using vector and algorithm?有人可以使用向量和算法来解释这个 c++ 程序吗?
【发布时间】:2015-05-02 06:02:05
【问题描述】:
#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;
}

这个程序完美运行,但我不知道它是如何工作的,我的意思是内部逐步操作。有人可以解释这段代码吗?我需要关于全局函数部分的详细解释。

【问题讨论】:

    标签: string vector data-structures stl


    【解决方案1】:

    它检查给定的字符串是否是回文。向量只不过是具有动态大小特性的数组。这里 reverse() 在 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;
    }
    

    【讨论】:

    • 是的,它应该被使用,他们在这个词上使用了反向功能。乍一看,我觉得它可能已被使用,我已经编辑了我的答案以反映这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多