I have implemented a program that produces a permuted index. Actually it is this exercise: http://stackoverflow.com/questions/4015016/what-is-a-permuted-index
Could anyone tell me if I did something wrong, and if it could be done better?
An input is for example:
The quick brown fox
And result:
The quick brown fox
The quick brown fox
The quick brown fox
The quick brown fox
main.cpp
#include "myImplementation.cpp"
using namespace std;
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;
}
int main() {
string phrase;
cout << "Please give me some phrase" << endl;
getline(cin, phrase);
vector <string> splitted = split(phrase);
vector<string> permuted = makePermutedIndex(splitted);
for (const auto i : permuted) {
cout << i << endl;
}
return 0;
}
myImplementation.cpp
#include <vector>
#include <sstream>
#include <algorithm>
using namespace std;
vector<string> concatLeftAndRight(const vector<string> &left, const vector<string> &right,
const string::size_type maxLengthOfLeftLine) {
vector<string> ret;
for (vector<string>::size_type i = 0; i != left.size(); ++i) {
std::stringstream ss;
ss << string(maxLengthOfLeftLine - left[i].size(), ' ')
<< left[i] << " " << right[i];
ret.push_back(ss.str());
}
return ret;
}
vector<string> makePermutedIndex(const vector<string> &splitted) {
vector<string> sorted(splitted);
std::sort(sorted.begin(), sorted.end());
string::size_type maxLengthOfLeftLine = 0;
vector<string> left;
vector<string> right;
for (auto index : sorted) {
string rightLine, leftLine;
bool indexEncountered = false;
for (auto word : splitted) {
if ((index != word) && !indexEncountered) {
leftLine += word;
leftLine += " ";
}
else {
indexEncountered = true;
rightLine += word;
rightLine += " ";
}
}
maxLengthOfLeftLine = max(maxLengthOfLeftLine, leftLine.size());
left.push_back(leftLine);
right.push_back(rightLine);
}
return concatLeftAndRight(left, right, maxLengthOfLeftLine);
}