限制在函数中作为参数传递的矢量位置

Limit the vector position to be passed in a function as parameter

本文关键字:参数传递 位置 函数      更新时间:2023-10-16

我正在考虑将索引限制在函数上传递。

main.cpp:

typedef vector<int *> my_int;
my_int a;
for (int i = 0; i < 8; ++i)
    a.push_back(i);  
calc1(a); //(Note:This is wrong) start the data from 0 until 3 only
calc2(a.begin() + 5); //(Note:This is wrong) start data from 4 to 7 only

我想把它传递给我的函数calc1()和calc2()。

int calc1(my_int *d)
{
    for (my_int::iterator it = d.begin(); i != d.end(); ++i)
        printf("%d ", *it);
}

输出应该是:

0 1 2 3

int calc2(my_int *d)
{
    for (my_int::iterator it = d.begin(); i != d.end(); ++i)
        printf("%d ", *it);
}

输出应该是:

4 5 6 7

我的语法不是特别准确,因为我还没有测试过。但是我想先知道如何实现这种情况

只写一个这样的函数就足够了

int calc( std::vector<int>::iterator first, std::vector<int>::iterator last );

并命名为

calc( my_int.begin(), std::next( my_int.begin(), 4 ) );
calc( std::next( my_int.begin(), 4 ), my_int.end() );

或者你可以这样声明函数

int calc_n( std::vector<int>::iterator first, size_t n );

并将其命名为

calc_n( my_int.begin(), 4 );
calc_n( std::next( my_int.begin(), 4 ), 4 );