jeudi 23 juin 2016
c++ string sorting and return indices
How do we sort strings and return their index?
I'm having 2 vectors myVector<char*> wordsVector and myVector<myVector<int>> pagesVector. For each word, there is a corresponding vector of pages. I'm trying to link them and sort words alphabetically.
I haven't found an effective way to sort both of them. So I sorted the stringsWordsVector, then compare words to the unsorted one (wordsVector) to find the index for each word in wordsVector like the code below, but it doesn't work
int main(int argc, const char * argv[]) {
myVector<char*> wordsVector; // storing each word as a char*
myVector<int> wordSize;
myVector<myVector<int>> pagesVector; // storing another vector containing list of pages for one word
////////Some code here for other functions, not related to code below
myVector<string> stringWordsVector;
//create a copy vector of strings from vector of char*
int wcounter;
for(auto it = wordsVector.begin(); it != wordsVector.end(); it++){
string s;
s.append((*it));
stringWordsVector.push_back(s);
wcounter++;
}
int size = stringWordsVector.size();
int index[size];
//string in sorted order
sort(stringWordsVector.begin(), stringWordsVector.end());
cout << "AFTER SORTING" << endl;
for(auto it = stringWordsVector.begin(); it != stringWordsVector.end(); it++){
cout << *it << endl;
}
//sorting indices
for(int i = 0; i < size; i++){
int indice = 0;
for(auto it = wordsVector.begin(); it != wordsVector.end(); it++){
string s;
s.append(*it);
if(s == stringWordsVector[i]){
//update the index
index[i] = indice;
break;
}
indice++;
}
}
}
Why does that happen? How can I fix it? And if you have better suggestions, I would appreciate it
Inscription à :
Publier les commentaires (Atom)
Aucun commentaire:
Enregistrer un commentaire