[英]How do I copy an initializer_list?
The following doesn't output anything for me. 以下内容对我来说没有任何输出。 From what I understand, the lifetime of an initializer_list is very limited and that copying an initializer_list doesn't copy the underlying elements.
据我了解,initializer_list的生存期非常有限,并且复制initializer_list不会复制底层元素。 I thought that passing by value would allow a move, and even an explicit move doesn't work.
我认为按值传递将允许采取行动,即使是明确的行动也不起作用。 I can't bind it to a reference and using a separate reference variable doesn't work here.
我无法将其绑定到引用,并且在此处无法使用单独的引用变量。 Even using a vector doesn't work??
即使使用向量也不起作用?
template <typename T, typename Pred>
void for_each(T t, const Pred& pred)
{
auto local = std::vector<typename T::value_type>{t.begin(), t.end()};
for (typename decltype(local)::size_type i = 0; i < local.size(); ++i)
pred(*(i + std::begin(local)));
}
void pred(char c)
{
std::cout << c << " ";
}
int main()
{
auto arr { 1, 2, 3 };
for_each(arr, pred);
return 0;
}
Your predicate is wrong : you pass it int
values, not char
, so your predicate is passed the characters 0x01, 0x02 and 0x03, which are not printable. 您的谓词是错误的:您将其传递给
int
值,而不是char
,因此您的谓词将传递不可打印的字符0x01、0x02和0x03。
You could use : 您可以使用:
void pred(int c)
{
std::cout << c << " ";
}
And your code now works fine . 和你的代码现在工作罚款 。
You could also just write a function template: 您还可以只编写一个功能模板:
template<typename T>
void pred(T c)
{
std::cout << c << " ";
}
Note: 注意:
Consider writing your loop with a for-range : 考虑使用for-range编写循环:
for (auto&& v : t)
pred(v);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.