如何在 C++ 中制作排列索引



我正在尝试实现一个产生排列索引的程序。实际上,这是这个练习:什么是排列索引?

我已经编写了一个函数,可以在字符串向量内对字符串进行旋转,但我不知道如何保存每个字符串上的旋转次数,以便以后能够取消旋转它以获得相同数量的旋转。实际上,我有将句子拆分为单词的函数和生成旋转的功能:

#include <iostream>
#include <vector>
using namespace std;

vector<string> bookImplementation(const vector<string> &splitted) {
    vector<string> result;
    result = generateRotations(splitted);
// WHAT NEXT?
}
vector<string> split(const string &s) {
    vector<string> ret;
    string::size_type i = 0;
    while (i != s.size()) {
        while (i != s.size() && isspace(s[i]))
            ++i;
        string::size_type j = i;
        while (j != s.size() && !isspace(s[j]))
            j++;
        if (i != j) {
            ret.push_back(s.substr(i, j - i));
            i = j;
        }
    }
    return ret;
}
vector<string> generateRotations(const vector<string> &splitted) {
    vector<string> result;
    for (vector<string>::size_type i = 0; i != splitted.size(); ++i) {
        string oneLine;
        vector<string> temp(splitted);
//HOW TO SAVE NUMBER OF ROTATIONS (i)?
        temp.insert(temp.begin(), temp.end() - i, temp.end());
        temp.erase(temp.end() - i, temp.end());
        for (vector<string>::size_type j = 0; j != temp.size(); ++j) {
            oneLine += " ";
            oneLine += temp[j];
        }
        result.push_back(oneLine);
    }
    return result;
}
int main() {
    string phrase;
    cout << "Please give me some phrase" << endl;
    getline(cin, phrase);
    vector <string> splitted = split(phrase);
    vector<string> permuted = bookImplementation(splitted);
    for (const auto i : permuted) {
        cout << i << endl;
    }
    return 0;
}

如果有人告诉我我做错了什么,那就太好了。

在不谈论算法的正确性的情况下,为了保存排列值 i,并从函数 generateRotations(..) 返回它,您必须创建一个结构来保存它。也许不是从 generateRotations 返回std::vector< std::string >,而是返回一个包含字符串及其排列数 i 的结构向量。

struct string_with_perm
{
    std::string str;
    int perm;
};

然后将函数更改为类似...

vector<string_with_perm> generateRotations(const vector<string> &splitted) {
    vector<string_with_perm> result;
    for (vector<string>::size_type i = 0; i != splitted.size(); ++i) {
        string oneLine;
        vector<string> temp(splitted);
//HOW TO SAVE NUMBER OF ROTATIONS (i)? NOW SAVED BELOW NEAR LAST LINE
        temp.insert(temp.begin(), temp.end() - i, temp.end());
        temp.erase(temp.end() - i, temp.end());
        for (vector<string>::size_type j = 0; j != temp.size(); ++j) {
            oneLine += " ";
            oneLine += temp[j];
        }
        string_with_perm sp;
        sp.str = oneLine;
        sp.perm = i;
        result.push_back(sp);
    }
    return result;
}

最新更新