我在Rust中创建了一个数据结构,我想为它创建迭代器.不可变的迭代器很容易.我目前有这个,它工作正常:
// This is a mock of the "real" EdgeIndexes class as
// the one in my real program is somewhat complex, but
// of identical type
struct EdgeIndexes;
impl Iterator for EdgeIndexes {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
Some(0)
}
fn size_hint(&self) -> (usize, Option<usize>) {
(0, None)
}
}
pub struct CGraph<E> {
nodes: usize,
edges: Vec<E>,
}
pub struct Edges<'a, E: 'a> {
index: EdgeIndexes,
graph: &'a CGraph<E>,
}
impl<'a, E> Iterator …Run Code Online (Sandbox Code Playgroud) 在 C 中创建自动扩展数组(如 C++ 的 std::vector)时,通常(或者至少是常见的建议)在每次填充时将数组的大小加倍,以限制调用量,以realloc避免尽可能复制整个数组。
例如。我们首先为 8 个元素分配空间,插入 8 个元素,然后为 16 个元素分配空间,再插入 8 个元素,再分配 32 个元素,等等。
但realloc如果可以扩展现有的内存分配,则不必实际复制数据。例如,以下代码在我的系统上仅执行 1 次复制(初始 NULL 分配,因此它不是真正的副本),即使它调用了realloc10000 次:
#include <stdlib.h>
#include <stdio.h>
int main()
{
int i;
int copies = 0;
void *data = NULL;
void *ndata;
for (i = 0; i < 10000; i++)
{
ndata = realloc(data, i * sizeof(int));
if (data != ndata)
copies++;
data = ndata;
}
printf("%d\n", copies);
}
Run Code Online (Sandbox Code Playgroud)
我意识到这个例子非常临床 - 现实世界的应用程序可能会有更多的内存碎片并且会做更多的副本,但即使我在循环之前进行一堆随机分配realloc,它也只会在 …
我在为点编写简单的传递几何着色器时遇到了一些问题。我想它应该是这样的:
#version 330
precision highp float;
layout (points) in;
layout (points) out;
void main(void)
{
gl_Position = gl_in[0].gl_Position;
EmitVertex();
EndPrimitive();
}
Run Code Online (Sandbox Code Playgroud)
当我没有指定几何着色器时,我在屏幕上显示了一堆点,但是当我尝试将此着色器链接到我的着色器程序时,没有显示任何点,也没有报告错误。
我正在使用 C# 和 OpenTK,但我认为这不是问题所在。
编辑:人们要求使用其他着色器,尽管我确实在不使用几何着色器的情况下测试了这些着色器,并且在没有几何着色器的情况下它们也能正常工作。
顶点着色器:
void main()
{
gl_FrontColor = gl_Color;
gl_Position = ftransform();
}
Run Code Online (Sandbox Code Playgroud)
片段着色器:
void main()
{
gl_FragColor = gl_Color;
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试学习Haskell,我已经创建了这个函数,它应该(我还没有真正测试过)读取varints:
import Data.Bits
import Data.Binary
getNum :: Get Int
getNum = do
l <- getWord8
let v = fromIntegral (clearBit l 7) :: Int
if testBit l 7
then do m <- getNum
return $ v .|. shiftL m 7
else return v
Run Code Online (Sandbox Code Playgroud)
它编译得很好,但我希望这能够读取任何类型的整数,而不仅仅是Int,所以我把它改为:
import Data.Bits
import Data.Binary
getNum :: (Bits a, Integral a) => Get a
getNum = do
l <- getWord8
let v = fromIntegral (clearBit l 7) :: a
if testBit l 7 …Run Code Online (Sandbox Code Playgroud)