c++ - 无法将 std::array 容器拆分为 2 个子部分

标签 c++ function c++11 pass-by-reference stdarray

我有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/

相关文章:

c++ - OpenCV Trackbar - 显示 double 值而不是 int

c++ - 'GPU activities' 和 'API calls' 在 'nvprof' 的结果中有什么区别?

c++ - 多项式代码

javascript - 将额外参数传递给 WebSQL 回调函数?

c++ - 在构造函数中初始化 <random> 类会导致段错误

C++ : "undefined reference to WeightCalc::getHeavier(int)"

c++ - 使用 Eigen 和为自动微分设计的自定义复数

c++ - Eclipse:注释整个代码而不会被其他注释打断

javascript - onclick 事件 - 为什么 Javascript 在加载时运行它

c++ - 如何返回唯一指针的数组/vector ?