我有std::array
6
的容器大小,必须先通过 3
std::array
的元素通过引用在一个函数中的容器和通过引用在另一个函数中的 Next 3 元素。但是我做不到。
我转换了 std::array<flaot,6> myarray
容器放入 c-style 数组并传递 func1(myarray)
和 func2(myarray+3)
并再次将 c-style 数组转换为 6
的 c++ 数组容器大小。
例如:-
std:array<float,6> myarray={1,2,3,4,5,6}
现在我想通过引用传递第一个函数中的第一个三元素和另一个函数中的下一个三元素。
最佳答案
std:array myarray={1,2,3,4,5,6};
Now I want to pass the first three elements in the first function and next three-element in another function by reference.
使用 std::array::iterator
s 代替。
将 std::array
的非 const 限定迭代器作为两个函数的参数传递并更改底层元素,这应该是最简单的方法。
也就是说,
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
关于c++ - 无法将 std::array 容器拆分为 2 个子部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57349061/