Embercode
✕
SortingQuick quiz

Multi-key and frequency order

8 questions. Covers Custom order by frequency.

Questions 1 to 5 of 8

  1. 1. Staff rows must be grouped by department, with names in A to Z order inside each department. Which two-pass method gives that result?
  2. 2. In a frequency comparator, why does the lesson read counts with count.at(a) instead of count[a]?
  3. 3. Predict the output of this program. ``cpp #include <algorithm> #include <iostream> #include <map> #include <vector> int main() { std::vector<int> nums{7, 3, 7, 1, 3, 7, 2}; std::map<int, int> count; for (int x : nums) { ++count[x]; } std::sort(nums.begin(), nums.end(), [&count](int a, int b) { if (count.at(a) != count.at(b)) { return count.at(a) > count.at(b); } return a < b; }); for (int x : nums) std::cout << x << ' '; std::cout << '\n'; } ``
  4. 4. Predict the output of this program. ``cpp #include <algorithm> #include <iostream> #include <string> #include <vector> int main() { std::vector<std::string> words{"pear", "fig", "kiwi", "apple", "lime"}; std::sort(words.begin(), words.end(), [](const std::string& a, const std::string& b) { if (a.size() != b.size()) return a.size() < b.size(); return a < b; }); for (const std::string& w : words) std::cout << w << ' '; std::cout << '\n'; } ``
  5. 5. Predict the output of this program. ``cpp #include <algorithm> #include <iostream> #include <string> #include <vector> struct Staff { std::string dept; std::string name; int salary; }; int main() { std::vector<Staff> rows{ {"it", "Kiran", 61000}, {"sales", "Priya", 52000}, {"it", "Divya", 61000}, {"it", "Arjun", 70000}, {"sales", "Anand", 48000}, }; std::sort(rows.begin(), rows.end(), [](const Staff& a, const Staff& b) { if (a.dept != b.dept) return a.dept < b.dept; if (a.salary != b.salary) return a.salary > b.salary; return a.name < b.name; }); for (const Staff& s : rows) std::cout << s.name << ' '; std::cout << '\n'; } ``

5 question(s) left on this page.