【问题标题】:Unable to split std::array container into 2 sub-part无法将 std::array 容器拆分为 2 个子部分
【发布时间】:2019-12-12 09:56:59
【问题描述】:

我有6 大小的std::array 容器,并且必须通过引用在一个函数中传递std::array 容器的第一个3 元素,并通过引用传递另一个函数中的下一个3 元素。但是我做不到。

我将std::array<flaot,6> myarray 容器转换为c-style 数组并传递func1(myarray)func2(myarray+3) 并再次将c-style 数组转换为@ 的c++ 数组容器987654330@尺寸。

例如:-

std:array<float,6> myarray={1,2,3,4,5,6} 

现在我想通过引用传递第一个函数中的第一个三元素和另一个函数中的下一个三元素。

【问题讨论】:

  • 请阅读How to Ask 或者minimal reproducible example。向我们展示你尝试了什么,解释它是如何失败的,包括错误,准确解释你卡在哪里。如果没有错误但输出错误,则学习使用调试器和/或如何添加日志输出。
  • 你试过func1(&amp;myarray[0])func2(&amp;marray[3])吗?

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


【解决方案1】:

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::iteratorlegacy 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 

【讨论】:

    猜你喜欢
    • 2015-12-13
    • 2021-02-18
    • 2013-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-17
    • 1970-01-01
    相关资源
    最近更新 更多