weima
weima

Reputation: 4912

How to use lambda function to print a pair<>?

I want to print a pair, e.g.

std::cout << make_pair(std::string,int) << endl;

But it doesn't compile because operator<<(ostream &, std::pair<std::string,int>) is not defined.

But because we now have c++11 with lambda functions, I can use lambda functions with a for_each expression to work on containers.

For the above case how could I supply an "in-place method" which can be used by ostream to print the pair?

Upvotes: 0

Views: 1690

Answers (2)

utnapistim
utnapistim

Reputation: 27365

For the above case how could I supply an "in-place method" which can be used by ostream to print the pair?

auto print = [&](const std::pair<std::string,int>& p) {
    std::cout << p.first << ", " << p.second << "\n";
};

std::map<std::string,int> sequence = { /* ... */ };
for_each(sequence.begin(), sequence.end(), print);
for(const auto& p: sequence)
    print(p);

or:

for_each(sequence.begin(), sequence.end(),
    [&](const std::pair<std::string,int>& p) {
        std::cout << p.first << ", " << p.second << "\n";
});

Either way, this is too complicated. You should write it like this:

for(const auto& p: sequence)
    std::cout << p.first << ", " << p.second << "\n";

Upvotes: 0

Sneftel
Sneftel

Reputation: 41484

Pairs (and other tuples) aren't really like containers, because their elements have heterogeneous types. They can't be iterated over in the normal way. So a lambda isn't really applicable here.

If you want, just define an output_pair template function which takes an ostream and a pair, and outputs the two elements of the pair. Or if you wanted to keep the extraction style, you could have output_pair return an output_pair_struct which does nothing but hold a copy of the tuple, and define an operator<< on the output_pair_struct which did the actual work, so that you could have std::cout << output_pair(mypair) << endl;.

Upvotes: 1

Related Questions