This project is read-only.

LINQ on std::map

Jun 11, 2014 at 5:21 PM

Or std::multimap for that matter...

How hard would it be to extend LINQ for C++ to handle map, multimap, things of this ilk?

int my_value = some_value;
std::map<int, int> my_map;
//or from_map, whichever naming convention is more obvious, makes the most sense
auto mapped = from(my_map) >> where([my_value](const std::pair<int, int>& p) { return p.first == value; }) >> to_vector();
//which should yield a std::vector<std::pair<int, int>>
Would be better than dancing around extracting mapped elements to a vector then running through LINQ-isms.

Doable? Thoughts?

Thank ye...
Jun 11, 2014 at 8:17 PM
Not sure exactly what you are asking for; I tried you code sample and it works in VS2013 & clang.

What happens when you try it?
Jun 11, 2014 at 8:27 PM
I am receiving the following error:
Error 1 error C2166: l-value specifies const object c:\program files (x86)\microsoft visual studio 11.0\vc\include\utility 196 1 CppSolutions
I tried in another function to do a standalone spike along the same lines, and that one at least builds.

I do typedef the std::pair and receive a std::function for the predicate, const&, but I can't see why that would cause any issues.
Jun 11, 2014 at 8:46 PM
Can you post the full compiler error and a snippet of the code that is being compiled?
Jun 11, 2014 at 8:55 PM
I figured it out. Well, the compiler taught me, anyhow.

The trick is to select away from the map::value_type as quickly as possible in order for subsequent clauses to work with settable (non-const) members.

auto predicated = from(paired) >> select([](const question_map_value_type& p) {
                    return paired_type(p.first, p.second); }) >> where(pp) >> to_vector();
After that, it did the trick.
Marked as answer by mwpowellhtx on 6/11/2014 at 1:02 PM