首页 > 解决方案 > 如何迭代作为指针传递的对数组参数?

问题描述

如何迭代作为指针传递的对数组参数?

我曾尝试用作参考对 &arr 。但它也不起作用。我可以pair<lli,lli> a[n];作为参考吗?

#pragma GCC optimize ("O3")
#pragma GCC target ("sse4")
#define LOCAL
#include <bits/stdc++.h>
using namespace std;

#define ff first
#define ss second
typedef long long int lli;
typedef unsigned long long int ulli;

void yeah( pair<lli,lli> *arr ){
    // cout << arr[0].ff;  100
    //this doesnt work :(
    for(auto e : arr){
        cout << e.ff << " " << e.ss << endl;
    }
}


int main() {
    int n = 10;
    pair<lli,lli> a[n];
    a[0].ff = 100;
    a[1].ss = 150;

    yeah(a);
}

这是我得到的错误

prog.cpp:在函数'void是(std :: pair )'中:prog.cpp:13:18:错误:没有匹配函数调用'begin(std :: pair &)'for(auto e:arr) { ^ ^

标签: c++pointersparameter-passingstd-pair

解决方案


具有固定大小数组的可能解决方案:

template<std::size_t size>
void foo(std::pair<int, int> (&arr)[size]) {
    for (auto e : arr) {
        ...
    }
}

constexpr std::size_t n = 10;   // should be known at compile time
std::pair<int, int> a[n];

foo(a);

推荐阅读