如何生成像列表理解这样的向量

che*_*gpu 16 c++ list-comprehension vector c++11

在C++ 11中,

vector<string> blockPathList;
for(int i = 0; i < blockNum; i++)
{
    blockPathList.push_back(desPath + "part" + to_string(i));
}
Run Code Online (Sandbox Code Playgroud)

是否有可能重写上面的代码,如列表理解,或更短,更简洁?

Bar*_*rry 10

您想使用第三方库吗?Eric Niebler的range-v3允许:

std::vector<string> blockPathList =
        view::ints(0, blockNum)
        | view::transform([&desPath](int i) {
            return desPath + "part" + std::to_string(i);
        });
Run Code Online (Sandbox Code Playgroud)

这就像你将要用C++获得的功能列表理解一样.

  • 你弄错了,他要求更短:) (9认同)
  • 这是一个难以理解的列表理解,但她*确实*要求它. (4认同)
  • @Rotem OP要求列表理解. (3认同)

Mar*_*erg 5

也不漂亮,但也应该完成工作:

int cur = 0;
std::vector<std::string> blockPathList(blockNum);
std::generate(blockPathList.begin(), blockPathList.end(),
        [&](){ return destPath + "part" + std::to_string(cur++); });
Run Code Online (Sandbox Code Playgroud)

不幸的是这个

  • 需要向量预先调整大小
  • 需要一个外部迭代变量(因为std::generate Generator它不带任何参数.

您还可以使用std::for_each:

std::vector<int> nums(blockNum);
std::iota(nums.begin(), nums.end(), 0);
std::for_each(nums.begin(), nums.end(), [&](int c) {
        blockPathList.push_back(destPath + "part" + std::to_string(c));
        });
Run Code Online (Sandbox Code Playgroud)

但这又是丑化的,因为std::iota不会产生范围.它使用迭代器填充现有范围,而不是在其自身中充当数字迭代器(当然,您可以通过实现或使用生成这些迭代器的东西来解决这个问题)

  • 如果使用`generate_n`(C++ 11)和`back_inserter`,则不必预先调整向量的大小. (4认同)

Dmi*_*yev 5

另一个例子(c++14):

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

template<typename CONTAINER, typename LAMBDA>
auto comprehension(CONTAINER&& container, LAMBDA&& lambda){
      std::vector<decltype(lambda(*container.begin()))> w;
      std::transform(container.begin(),container.end(),std::back_inserter(w), lambda);
      return w;
}
int main(){
    auto&& ints = {1,2,3,4,5};
    auto&& squares = comprehension(ints,[](auto i){ return i*i; });

    for( auto s : squares){ std::cout << s << ' '; }
    std::cout << '\n';
}
Run Code Online (Sandbox Code Playgroud)

输出:

1 4 9 16 25
Run Code Online (Sandbox Code Playgroud)