Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate vector like list comprehension

Tags:

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?

like image 739
chenzhongpu Avatar asked Mar 31 '16 17:03

chenzhongpu


People also ask

Does C++ have list comprehension?

Introduction. The library introduces Pythons list comprehension to C++ based on boost::phoenix .

How much faster is list comprehension than for loop?

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.

Is list comprehension faster than for loop Python?

Because of differences in how Python implements for loops and list comprehension, list comprehensions are almost always faster than for loops when performing operations.

Is it possible to use list comprehension with a string?

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.


1 Answers

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++.

like image 149
Barry Avatar answered Sep 28 '22 11:09

Barry