So I'm supposed to write a function that takes a vector of strings and sort it alphabetically but based on the last character of each string. For example, {“apple”, “banana”, “carrot”}, would be {“banana“, “apple“, “carrot”} because the last “a” in banana comes before the “e” in “apple” and the “t” in “carrot”.
This is my code so far:
#include <iostream>
#include <vector>
#include <string>
void SortByReverse(std::vector<std::string> &v)
{
std::vector<int> int_v;
for(int i = 0; i < v.size(); i++) // for loop to store ascii values of each last ch
{
int last_ch_index = v[i].size() - 1;
int_v.push_back(int(v[i][last_ch_index]));
std::sort(int_v.begin(), int_v.end()); // sort ascii value vector in ascending order
}
for(int u = 0; u < int_v.size(); u++) // iterate through ascii values vector and print corresponding str
{
for(int q = 0; q < v.size(); q++)
{
int last_ch_index = v[q].size() - 1;
if(int_v[u] == int(v[q][last_ch_index]))
{
std::cout << v[q] << "\n";
}
}
}
}
int main()
{
std::vector<std::string> v = {"apple", "banana", "carrot"};
SortByReverse(v);
}
which outputs my strings in the correct order but I don't know how to change the order in the vector itself. I tried doing
v[u] = v[q]
but that outputs "banana, banana, carrot" because it assigns "banana" to "apple" to when "apple" is supposed to be printed, you just get "banana" again. Surely there is a way to add on to the code I already have and fix this issue but I don't know how.