C ++中有没有办法从数组中获取子数组?

时间:2012-11-27 01:39:40

标签: c++ arrays

我现在有一个大脑放屁,我正在寻找一种快速的方法来取一个数组并将其中的一半传递给一个函数。如果我有一个十个元素的数组A,在某些语言中我可以将类似A [5:]的东西传递给函数并完成它。在c ++中是否有类似的构造?显然我想避免和排序循环函数。

2 个答案:

答案 0 :(得分:7)

是。在普通的C中你使用指针,但在C ++中你可以使用任何类型的迭代器(指针可以被认为是迭代器)。

template<typename Iter>
void func(Iter arr, size_t len) { ... }

int main() {
    int arr[10];
    func(arr, 10);    // whole array
    func(arr, 5);     // first five elements
    func(arr + 5, 5); // last five elements

    std::vector<Thing> vec = ...;
    func(vec.begin(), vec.size());          // All elements
    func(vec.begin(), 5);                   // first five
    func(vec.begin() + 5, vec.size() - 5);  // all but first 5

    return 0;
}

典型的技巧是将指针传递给数组的第一个元素,然后使用单独的参数传递数组的长度。不幸的是,没有边界检查,所以你必须小心把它弄好,否则你会乱写你的记忆。

您也可以使用半开范围。这是最常用的方法。标准库中的许多函数(如std::sort)都以这种方式工作。

template<class Iter>
void func(Iter start, Iter end) { ... }

int main() {
    int arr[10];
    func(arr, arr + 10);       // whole array
    func(arr, arr + 5);        // first five elements
    func(arr + 5, arr + 10);   // last five elements

    std::vector<Thing> vec = ...;
    func(vec.begin(), vec.end());       // whole vector
    func(vec.begin(), vec.begin() + 5); // first five elements
    func(vec.begin() + 5, vec.end());   // all but the first five elements

    return 0;
}

再次,没有边界检查。

答案 1 :(得分:0)

我也有相同的用法,但我使用vector并使用了语法

 public struct Values
    {
        int value1 { get; set; }
        int value2 { get; set; }

        public Values(int value1, int value2)
        {
            if (value1 <= value2)
            {
                this.value1 = value1;
                this.value2 = value2;
            }
            else
            {
                this.value1 = value2;
                this.value2 = value1;
            }
        }
    }
    public static readonly Dictionary< int, Values> dict = new Dictionary<int, Values>
{
    { 0 ,new Values(5, 6) },
    { 1 ,new Values(4, 6)},

};
    private void button1_Click(object sender, EventArgs e)
    {
        foreach (KeyValuePair<int, Values> item in dict.ToList())
        {
            Values tile = item.Value;
            Console.WriteLine("Key: {0}, Value: {1}", item.Key,  tile.value1);

        }

    }