Reference to an object disregarding mutation - what's the trick?

Regan Heath regan at netmail.co.nz
Tue May 29 11:24:45 PDT 2007


You can replace your for loop with a memmove call, heres some code to chew on:

import std.stdio, std.random;

extern(C) void *memmove(void *,void *,size_t);

struct Node { int x; }

Node[] nodeList;

static this()
{
	nodeList.length = 10;
	foreach(i, ref n; nodeList) n.x = i*2;
	printNodes(nodeList);
}

uint findNode(Node[] nodeList, ref Node nn)
{
	foreach(i, n; nodeList) { if (n.x > nn.x) return i; }	
	return nodeList.length;
}

void insertNode(ref Node[] nodeList, ref Node nn)
{
	int i = findNode(nodeList,nn);
	
	nodeList.length = nodeList.length + 1;
	if (i < nodeList.length-1) {
		memmove(&nodeList[i+1], &nodeList[i], 
			Node.sizeof * (nodeList.length-i-1));
	}
	nodeList[i] = nn;
}

void printNodes(Node[] nodeList)
{
	foreach(i, n; nodeList) {
		writef(n.x,(i<nodeList.length-1)? "," : "\n");
	}
}

void randomNode(ref Node[] nodeList)
{
	Node nn;
	nn.x = rand()%20;
	writefln("ADD:",nn.x);
	insertNode(nodeList,nn);
}

void main()
{
	randomNode(nodeList);
	randomNode(nodeList);
	randomNode(nodeList);
	randomNode(nodeList);
	printNodes(nodeList);
}

Regan Heath



More information about the Digitalmars-d mailing list