我正在尝试实现一个产生置换索引的程序。 Acctualy是这个练习: What is a permuted index?
我已经编写了一个函数,它对字符串向量内的字符串进行旋转,但我不知道如何保存每个字符串上的旋转次数,以便能够在以后旋转相同的旋转次数时将其旋转。 实际上我有一个功能,将一个句子分成单词和生成旋转的函数:
#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;
}
如果有人告诉我我做错了什么会很好。
答案 0 :(得分: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;
}