有没有映射向量的好方法?下面是我的意思的一个例子:
vec0 = [0,0,0,0,0,0,0,0,0,0,0]
vec1 = [1,4,2,7,3,2]
vec2 = [0,0,0,0,0,0,0,0,0]
vec2 = [7,2,7,9,9,6,1,0,4]
vec4 = [0,0,0,0,0,0]
mainvec =
[0,0,0,0,0,0,0,0,0,0,0,1,4,2,7,3,2,0,0,0,0,0,0,0,0,0,7,2,7,9,9,6,1,0,4,0,0,0,0,0,0]假设mainvec并不存在(我只是向您展示它,以便您可以看到头脑中的一般数据结构。
现在假设我想要mainvec(12),它应该是4。有没有一种好的方法来映射这些向量的调用,而不只是把它们缝合到一个mainvec中?我意识到我可以编写一堆if语句来测试mainvec的索引,然后我可以根据调用在其中一个向量中的位置来偏移每个调用,例如:
mainvec(12) = vec1(1)我可以这样做:
mainvec(index)
if (index >=13)
vect1(index-11);我想知道有没有一种简明的方法可以不用if语句就能做到这一点。有什么想法吗?
发布于 2010-06-15 06:02:09
你在找这样的东西吗?
using System.Collections.Generic;
namespace Test
{
class Program
{
static void Main(string[] args)
{
int[] vec0 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
int[] vec1 = { 1, 4, 2, 7, 3, 2 };
int[] vec2 = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
int[] vec3 = { 7, 2, 7, 9, 9, 6, 1, 0, 4 };
int[] vec4 = { 0, 0, 0, 0, 0, 0 };
List<int> temp = new List<int>();
temp.AddRange(vec0);
temp.AddRange(vec1);
temp.AddRange(vec2);
temp.AddRange(vec3);
temp.AddRange(vec4);
int[] mainvec = temp.ToArray();
}
}
}发布于 2010-06-15 05:38:50
我会使用交错数组。
你仍然需要一个循环,但是你可以在没有冗余的情况下保留单独的向量:
var mainvec = new int[][]{vec0, vec1, vec2, vec3, vec4};
int desiredInd = 12, totalInd = 0, rowInd = 0, result;
while(rowInd < mainvec.Length && (totalInd + mainvec[rowInd].Length) <= desiredInd)
{
totalInd += mainvec[rowInd++].Length;
}
if(rowInd < mainvec.Length && (desiredInd - totalInd) < mainvec[rowInd].Length)
{
result = mainvec[rowInd][desiredInd - totalInd];
}发布于 2010-06-15 05:41:38
我将创建一个接收长度数组的类,并有一个方法为组合列表中的给定索引在数组中提供array number和Index。
它将由一个类和一个索引器包装,该类将获得对实际数组的引用,以将您带到正确的元素。
https://stackoverflow.com/questions/3041130
复制相似问题