6
I made this code but it doesn’t work right, it inserts in alphabetical order backwards.
void inserirNomeNaLista(vector<string> &lista)
{
vector<string>::iterator itr;
string nome;
cout << "Digite o nome para ser inserido na lista: ";
cin >> nome;
if (lista.size() == 0)
{
lista.push_back(nome);
}
else
{
for (itr = lista.begin(); itr != lista.end(); itr++)
{
if (*itr > nome)
{
lista.insert(itr, nome);
}
break;
}
}
}
Are you sure he’s always inserting backwards? His
break
is outside the block ofif (*itr > nome)
(instead of being inside it), which causes it to enter only if the new string is less than or equal to the string of the first element of the array. Because of thebreak
, the loop always ends after the first interaction.– Luiz Vieira