'Using for_each to print the highest value in a vector

I've this code:

vector<pair<double, complex<double>>> vC;
GetFourierCoeffs(N, t, A, vC);

so vC is a vector that contains pairs with doubles and complex numbers I need to use for_each to print the 6 complex numbers with higher norm, how can i do it?

I´ve tried creating a new vector, but I need to do it only with for_each



Solution 1:[1]

I didn't understand how creating a new vector can help printing the current one.

Anyway - you can try the following code for printing the content of vC:

for (auto const & elem : vC)
{
    auto const & doubleValue = elem.first;
    auto const & complexValue = elem.second;
    // TODO: print doubleValue and complexValue in your print method of choice.
}

You can also use std::for_each to achieve a similar result:

std::for_each(vC.begin(), vC.end(), 
    [](pair<double, complex<double>> const & elem)
{
    auto const & doubleValue = elem.first;
    auto const & complexValue = elem.second;
    // TODO: print doubleValue and complexValue in your print method of choice.
});

Regarding getting specific values (6 with highest norm) - you can sort the vector with a custom comparator that uses the norm.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1