简体   繁体   中英

can I make std::list insert new elements with order ? or got to use std::sort?

If I want to use std::list and that the new elements inserted to the list will be inserted to the right position in relation to a compare function - can I do it ? or I have to use std::sort after each insertion?

You can use:

  • std::set if your elements a immutable
  • std::map if your elements have immutable keys, but should have mutable values
  • std::list and looking up the insertion position

std::list with std::lower_bound:

#include <algorithm>
#include <list>
#include <iostream>

int main()
{
    std::list<int> list;
    int values[] = { 7, 2, 5,3, 1, 6, 4};
    for(auto i : values)
        list.insert(std::lower_bound(list.begin(), list.end(), i), i);
    for(auto i : list)
        std::cout << i;
    std::cout << '\n';
}

Alternatively you may populate an entire std::vector and sort it afterwards (Note: std::sort can not operate on std::list::iterators, they do not provide random access):

#include <algorithm>
#include <vector>
#include <iostream>

int main()
{
    std::vector<int> vector = { 7, 2, 5,3, 1, 6, 4};
    std::sort(vector.begin(), vector.end());
    for(auto i : vector)
        std::cout << i;
    std::cout << '\n';
}

Note: The performance of a list with manual lookup of the insertion position is the worst O(N²).

Yes you can. Try something like following, just change compare function and type if needed.

#include <list>

inline
int compare(int& a, int&b) {
    return a - b;
}

template<typename T>
void insert_in_order(std::list<T>& my_list, T element, int (*compare)(T& a, T&b)) {
    auto begin = my_list.begin();
    auto end = my_list.end();
    while ( (begin != end) &&
        ( compare(*begin,element) < 0 )      ) {
        ++begin;
    }
    my_list.insert(begin, element);
}

int main() {
    std::list<int> my_list = { 5,3,2,1 };
    my_list.sort();                              //list == { 1,2,3,5}
    insert_in_order<int>(my_list, 4, &compare);  //list == {1,2,3,4,5}
}

You have three options:

  1. Sort after every insertion
  2. Find the right index and insert at that index
  3. Use an std::set (recommended)

Example for third option:

#include <iostream>
#include <set>

int main ()
{
  int myints[] = {75,23,65,42,13};
  std::set<int> myset (myints,myints+5);

  std::cout << "myset contains:";
  for (std::set<int>::iterator it=myset.begin(); it!=myset.end(); ++it)
    std::cout << ' ' << *it;

  std::cout << '\n';

  return 0;
}

Output:

myset contains: 13 23 42 65 75

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM