1

how do i iterate the pair array arguments passed as a pointer ?

i had tried to use as reference pair &arr . but it doesnt worked either . can i pass pair<lli,lli> a[n]; as reference ??

#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);
}

this is the error im getting

prog.cpp: In function 'void yeah(std::pair)': prog.cpp:13:18: error: no matching function for call to 'begin(std::pair&)' for(auto e : arr){ ^ ^

Blaze
  • 16,736
  • 2
  • 25
  • 44
tusse
  • 21
  • 3
  • 1
    maybe use std::vector? or array? – Raffallo Nov 12 '19 at 09:18
  • why cant i use this only sir – tusse Nov 12 '19 at 09:18
  • `arr` tells `for` where to start, but how would `for` know where to stop? – Evg Nov 12 '19 at 09:20
  • thanks for teaching i know something now – tusse Nov 12 '19 at 09:21
  • 2
    [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) – Evg Nov 12 '19 at 09:27
  • im doing competitive programming so it doesnt matter @Evg – tusse Nov 12 '19 at 09:38
  • 1
    @tusse IMO, it does matter. Competitive programming should not be a synonym for sloppy programming. Don't pick bad habits from the very beginning. – Evg Nov 12 '19 at 09:40
  • unfortunately common practices in competitive programming are opposing common practices elsewhere, eg `#define ff first` and the typedefs should be a no-go when you ask others to read your code, because they may save some keystrokes for you but obfuscate the code for anybody else – 463035818_is_not_an_ai Nov 12 '19 at 10:04

2 Answers2

4

A possible solution with fixed-size arrays:

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);
Evg
  • 25,259
  • 5
  • 41
  • 83
1

I would recommend ditching the VLA (which is not part of C++ anyway) and use std::vector instead. Include <vector> and change the declaration to this:

std::vector<std::pair<lli, lli>> a(n);

And the function's signature to:

void yeah(std::vector<std::pair<lli, lli>> &arr)
Blaze
  • 16,736
  • 2
  • 25
  • 44