我正在尝试编写一个简单的模板函数来打印某个容器的每个元素,而不使用for循环.到目前为止,我有
#include <iostream>
#include <vector>
#include <algorithm>
template <typename T> void print_with_space(T x){
std::cout << x << ' ';
}
template <typename T> void print_all(T beg, T end){
std::for_each(beg, end, print_with_space<int>);
std::cout << '\n';
}
int main(){
int a[] = {1, 2, 3};
std::vector<int> v(a, a+3);
print_all(v.begin(), v.end());
return 0;
}
Run Code Online (Sandbox Code Playgroud)
代码编译并运行,但只是因为我把print_with_space<int>内部的实现print_all.我想在print_with_space那里有明显的原因,但是代码不能编译.我该怎么做呢?
我试图使用循环宏过滤列表.如果我做
(loop for x in (list 1 2 3 4) collect x)
Run Code Online (Sandbox Code Playgroud)
我只是回到同一个列表,这是有道理的.但是,我想做点什么
(loop for x in (list 1 2 3 4) collect x if (evenp x))
Run Code Online (Sandbox Code Playgroud)
然后(2 4)回来,但这不合法.出于某种原因,我无法在其他文档中找到相应的语法.这可能吗?
在Scheme中,如果我想要一个列表,请说(1 2 3),我会写'(1 2 3).通常情况下,这很好,但它实际上相当于(quote (1 2 3)),与之不完全相同(list 1 2 3).这会产生不同结果的一个例子:
'(1 2 (+ 0 3)) -> (1 2 (+ 0 3))
(list 1 2 (+ 0 3)) -> (1 2 3)
Run Code Online (Sandbox Code Playgroud)
第二行是否有语法糖?对于矢量有.例如:
#(1 2 (+ 0 3)) -> #(1 2 3)
(vector 1 2 (+ 0 3)) -> #(1 2 3)
Run Code Online (Sandbox Code Playgroud)
如果列表中没有这样的糖,那将是非常具有讽刺意味的,因为列表的使用方式比Scheme中的向量更常用!
scheme ×2
c++ ×1
common-lisp ×1
foreach ×1
functor ×1
lisp ×1
loops ×1
mit-scheme ×1
stl ×1
templates ×1