c++ - std::sort that also keeps track of number of unique entries at each level -
say have std::vector. vectors contain numbers. let's take std::vector
1,3,5,4,3,4,5,1,6,3
std::sort<std::less<int>> sort
1,1,3,3,3,4,4,5,5,6,
how ammend sort @ same time sorting, computes quantity of numbers @ same level. in addition sorting, compile following dictionary [level int]
std::map<level, int> <1, 2> <2, 3> <3, 2> <4, 2> <5, 1> <6, 1>
so there 2 1's, 3 3's, 2 4's, , on.
the reason [think] need because don't want sort vector, once again, compute number of duplicates @ each level. seems faster both in 1 pass?
thank all! bjskishore123 closest thing asking, responses educated me. again.
as stated @bjskishore123, can use map guarantee correct order of set. bonus, have optimized strucutre search (the map, of course).
inserting/searching in map takes o(log(n)) time, while traversing vector o(n). so, alghorithm o(n*log(n)). wich same complexity sort algorithm needs compare elements: merge sort or quick sort, example.
here sample code you:
int tmp[] = {5,5,5,5,5,5,2,2,2,2,7,7,7,7,1,1,1,1,6,6,6,2,2,2,8,8,8,5,5}; std::vector<int> values(tmp, tmp + sizeof(tmp) / sizeof(tmp[0])); std::map<int, int> map_values; for_each(values.begin(), values.end(), [&](int value) { map_values[value]++; }); for(std::map<int, int>::iterator = map_values.begin(); != map_values.end(); it++) { std::cout << it->first << ": " << it->second << "times"; }
output:
1: 4times 2: 7times 5: 8times 6: 3times 7: 4times 8: 3times
Comments
Post a Comment