I wonder if there's a way to begin reading from an arbitrary position in a array. E.g. if I have a array of size 10 and it begins reading from position 4. Then it should continue on reading 开发者_StackOverflowfrom position 5, 6, 7, 8, 9, 0, 1, 2, 3
I was uncertain with tag, so if have picked wrong tag please do change it for me.
Yes, you can index using the modulo operation which is written as %
in most languages:
x = list[i % list.length]
This will give you the desired effect of wrapping around when you reach the end of the list instead of attempting to index out of bounds.
This assumes 0-based indexing. If you use 1-based indexing you have to add one to the result of the modulo operation.
offset = 4;
for(i=0; i<n; i++)
cout << x[(i+offset)%n] << ' ';
It depends on what you mean by "list". Traditionally in computer science, "list" usually means "linked list". In this case, you have to traverse the list in order to get to a particular element.
If you need/want to be able to start reading from arbitrary positions efficiently, you probably want to avoid linked lists, but the exact alternatives you have (easily) available will vary with the programming language, libraries, etc., you're using.
Edit: for an array, it's generally trivial -- just specify the starting position directly, and take the remainder after dividing by the array size.
One option is to make the list circular (like they do it in the Linux kernel).
精彩评论