1

how can I efficiently modify the elements of these two lists using stl algorithms:

std::list<std::pair<double, string> > listPair(10);
std::list<double> listA(10);

And in such a way that the first pair-element gets the corresponding double value from listA?

4

2 に答える 2

3

Try using C++11 lambdas

#include <algorithm>
#include <list>
#include <string>
#include <utility>

int main()
{
    std::list<std::pair<double, std::string> > listPair(10);
    std::list<double> listA(10);

    // original question: assign double of listA to listPair
    std::transform(
        listA.begin(), listA.end(), listPair.begin(), listPair.begin(), 
        [](double d, std::pair<double, std::string> const& p) {
            return std::make_pair(d, p.second);
        }
    ); 

    // other way around: assign double from listPair to listA
    std::transform(
        listPair.begin(), listPair.end(), back_inserter(listA), 
        [](std::pair<double, std::string> const& p) {
            return p.first;
        }
    );

    return 0;
 }
于 2012-07-13T10:30:09.667 に答える
3

Here I assume listPair is already filled, because there's no way to get that string otherwise.


You could loop through the collections directly.

auto a_cur = listA.begin(), a_end = listA.end();
auto pair_cur = listPair.begin();
for (; a_cur != a_end; ++ a_cur, ++ pair_cur) {
    pair_cur->first = *a_cur;
}

or use the "binary" version of std::transform, but this will involve copying the string:

std::transform(listA.begin(), listA.end(), listPair.begin(), listPair.begin(),
               [](double a, std::pair<double, string> b) {
                   return std::make_pair(a, b.second);
               });
于 2012-07-13T10:33:13.217 に答える