std:array myarray={1,2,3,4,5,6}; 现在我想在第一个函数和下一个函数中传递前三个元素
引用另一个函数中的三元素。
请改用std::array::iterator。
将std::array 的非常量限定迭代器作为两个函数的参数传递并更改底层元素,这应该是最简单的。
也就是说,
func1(myarray.begin(), myarray.begin() + 3); // first function
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
func2(myarray.begin() + 3, myarray.end); // second function
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
您可以这样做,因为 std::array::iterator 是 legacy random access iterators。
以下是示例代码。 (See online)
#include <iostream>
#include <array>
using Iter = std::array<int, 6>::iterator;
void func1(Iter first, const Iter second)
{
while (first != second) // do something in the range
{
*first = *first + 1; // increment the element by one
++first;
}
}
// same for the func2
void func2(Iter first, const Iter second)
{
while (first != second) { /*do something in the range */ }
}
int main()
{
std::array<int, 6> myarray{ 1,2,3,4,5,6 };
std::cout << "Before calling the func1: ";
for (const int ele : myarray) std::cout << ele << " ";
// pass the iterator range of first three elements
func1(myarray.begin(), myarray.begin() + 3);
std::cout << "\n";
std::cout << "After the func1 call: ";
for (const int ele : myarray) std::cout << ele << " ";
return 0;
}
输出:
Before calling the func1: 1 2 3 4 5 6
After the func1 call: 2 3 4 4 5 6