LearnFrenzy
Sign in Take a free test

STL Algorithms and Iterators · STL Algorithm Programs · Question 6

Parse and analyse CSV-like data with ranges in C++ Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

Split lines of "name,city,salary", keep employees from Pune with views::filter, sort them by salary with a projection and print names and the total using ranges algorithms.

Solution
main.cpp
#include <algorithm>
#include <iostream>
#include <numeric>
#include <ranges>
#include <sstream>
#include <string>
#include <vector>

struct Emp { std::string name, city; int salary; };

Emp parse(const std::string& line) {
    std::istringstream in(line);
    Emp e;
    std::getline(in, e.name, ',');
    std::getline(in, e.city, ',');
    in >> e.salary;
    return e;
}

int main() {
    std::vector<std::string> lines{"Asha,Pune,82000", "Ravi,Delhi,64000", "Meena,Pune,91000", "John,Pune,58000", "Zoya,Mumbai,77000"};
    std::vector<Emp> all;
    std::ranges::transform(lines, std::back_inserter(all), parse);

    auto pune = all | std::views::filter([](const Emp& e) { return e.city == "Pune"; });
    std::vector<Emp> sorted(pune.begin(), pune.end());
    std::ranges::sort(sorted, std::ranges::greater{}, &Emp::salary);

    for (const auto& e : sorted) std::cout << e.name << ' ' << e.salary << '\n';
    auto salaries = sorted | std::views::transform(&Emp::salary);
    std::cout << "total " << std::accumulate(salaries.begin(), salaries.end(), 0L) << '\n';
    return 0;
}

Output Verified by compiling and running

Meena 91000
Asha 82000
John 58000
total 231000

ranges::transform parses into a vector, a filter view selects without copying, a projection sorts by salary, and a transform view over a member pointer feeds accumulate.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links