Does anyone know how to enter names in alphabetical order in a c ++ vector?


I made this code but it does not work right, it inserts alphabetically in reverse.

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)
        for (itr = lista.begin(); itr != lista.end(); itr++)
            if (*itr > nome)
                lista.insert(itr, nome);
asked by anonymous 22.02.2014 / 05:24

3 answers


If you plan to have your list sorted, the simplest way to do this is to directly use a std::set , which is ordered and does not allow duplicates. The code looks like this:

std::set<std::string> nomes;

for (auto& nome : nomes)
    std::cout << nome << std::endl; // Amanda, Maria, Pedro


However, if you want to keep using std::vector , you can search for the position if insertion using std::lower_bound . But note that this function only works correctly on already ordered lists ( binary search ). So:

void sortedInsert(std::vector<std::string>& vec, std::string value) {
    auto it = std::lower_bound(vec.begin(), vec.end(), value);
    vec.insert(it, std::move(value));

std::vector<std::string> nomes;
sortedInsert(nomes, "Pedro");
sortedInsert(nomes, "Amanda");
sortedInsert(nomes, "Maria");

for (auto& nome : nomes)
    std::cout << nome << std::endl; // Amanda, Maria, Pedro

With a few more templates: (coliru)

22.02.2014 / 11:46

I suggest you take a look at the standard STL algorithms. To resolve this exact problem, you already have lower_bound

#include <algorithm>

void inserirNomeNaLista(std::vector<string> &lista)
  std::string nome;
  std::cout << "Digite o nome para ser inserido na lista: ";
  std::cin >> nome;

  typedef std::vector<std::string>::iterator VecIter;
  VecIter itr = std::lower_bound(lista.begin(), lista.end(), nome);    
  lista.insert(itr, nome);

It searches in a sequence (pair of iterators) the point at which to insert an item so that the sequence is in ascending order. It is efficient because it performs binary search, but only works if the sequence is always ordered . But if you only use it to insert elements into a vector there is no problem, because in this case the inserts will always be in order.

Now if this is an exercise, and you can not use the default algorithms, I believe your error is the position of break , as already explained n Luiz Vieira's comment .

22.02.2014 / 11:41

Friend, STL already makes the sort () method available to you. It lexicographically parses the strings and sorts them. Here's an example.

#include <algorithm> //Para o sort()
#include <iostream> //Para o cout
#include <vector>  //Para o vector<>()
#include <string> //Para a string

int main() {
    std::vector<std::string> v;
    v.push_back("bac"); v.push_back("abc"); v.push_back("cab"); v.push_back("cba");
    for(int i = 0; i < v.size(); i++) std::cout << v[i] << std::endl;
11.03.2014 / 22:25