In C++11,
vector<string> blockPathList; for(int i = 0; i < blockNum; i++) { blockPathList.push_back(desPath + "part" + to_string(i)); }
Is it possible to re-write the code above like list comprehension, or shorter and more concise?
Introduction. The library introduces Pythons list comprehension to C++ based on boost::phoenix .
As we can see, the for loop is slower than the list comprehension (9.9 seconds vs. 8.2 seconds). List comprehensions are faster than for loops to create lists. But, this is because we are creating a list by appending new elements to it at each iteration.
Because of differences in how Python implements for loops and list comprehension, list comprehensions are almost always faster than for loops when performing operations.
List comprehension in Python is an easy and compact syntax for creating a list from a string or another list. It is a very concise way to create a new list by performing an operation on each item in the existing list. List comprehension is considerably faster than processing a list using the for loop.
Do you want to use third-party libraries? Eric Niebler's range-v3 allows for:
std::vector<string> blockPathList = view::ints(0, blockNum) | view::transform([&desPath](int i) { return desPath + "part" + std::to_string(i); });
That's about as functional list-comprehension-y as you're going to get in C++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With