简体   繁体   中英

How to simplify this code?

I test concurrency in my program and write the following code

vector<unique_ptr<future<double>>> results;
for (unsigned i = 0; i != 16; ++i)
{
     unique_ptr <future<double>> result(new future<double >{ async(once) });
     results.push_back(move(result));
}
auto ave = (results[0]->get() + results[1]->get() + results[2]->get() +\
    results[3]->get() + results[4]->get() + results[5]->get() +\
    results[6]->get() + results[7]->get() + results[8]->get() + \
    results[9]->get() + results[10]->get() + results[11]->get() + \
    results[12]->get() + results[13]->get() + results[14]->get() + \
    results[15]->get()) / 16.0;

once is a function which takes no parameter and returns a double, for instance, return a random number in [0,1]. The ave average the 16 results. I find the code is really redundant what if I average for 100 times. Use a loop maybe solve the problem but I'm not sure whether the concurrency is still working, so I wander how to simplify the code?

Learn the C++ algorithms :

using type = unique_ptr<future<double>>;
auto mean = std::accumulate(results.begin(), results.end(), 0.0,
        [](double a, type const& b) { return a + b->get(); }) / results.length();

C++ algorithms is the way to go, as Konrad Rudolph pointed out. This answer is only an extension if algorithms cannot be used for whatever reason. Without algorithms, you could use another for loop. This monstrous block of code

auto ave = (results[0]->get()  + results[1]->get()  + results[2]->get()  +
            results[3]->get()  + results[4]->get()  + results[5]->get()  +
            results[6]->get()  + results[7]->get()  + results[8]->get()  +
            results[9]->get()  + results[10]->get() + results[11]->get() +
            results[12]->get() + results[13]->get() + results[14]->get() +
            results[15]->get()) / 16.0;

could be replaced by

auto it = results.begin();
auto ave = (*(it++))->get(); // so you can still use auto
for(/* it already initialized */; it != results.end(); ++it)
    ave += (*it)->get();
ave /= results.size();

which will work for any number of elements in your vector .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM