For C++11 there's always the lambda inplace initialization trick:
const auto vc = [&]{
std::vector<const char*> tmp(v.size());
std::transform(v.begin(), v.end(), tmp.begin(), convert);
return tmp;
}();
or
const auto vc = [&]{
std::vector<const char*> tmp;
tmp.reserve(v.size());
std::transform(v.begin(), v.end(), back_inserter(tmp), convert);
return tmp;
}();
See it Live On Coliru
That's said, I'd prefer the Boost Range adaptors: (also Live On Coliru)
const auto vc = boost::copy_range<std::vector<const char*> >(v | transformed(convert));
#include <algorithm>
#include <vector>
#include <iterator>
#include <string>
#include <functional>
#include <iostream>
int main()
{
const std::vector</* const */ std::string> v { "test", "goodbye" };
auto convert = std::mem_fn(&std::string::c_str);
const auto vc = [&]{
std::vector<const char*> tmp;
tmp.reserve(v.size());
std::transform(v.begin(), v.end(), back_inserter(tmp), convert);
return tmp;
}();
for (auto cc : vc)
std::cout << cc << "
";
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…