TransWikia.com

How to pass array to funtion to use as range based for loop

Stack Overflow Asked by Aniket Ujgare on February 10, 2021

void sortArray(int arr[])
{
    int size = sizeof(arr)/sizeof(arr[0]);
    int count0s{0},count1s{0},count2s{0};
     for (int n: arr)
     {

     }

}
int main()
{
    //some code here including creating array arr
        sortArray(arr);
        TestCases--;
    }

    return 0;
}

I want to use range-based for loop in sortArray function but I don’t know how to pass it.
enter image description here

3 Answers

since c++20, you can use std::span<T>

void func(std::span<int> values) {
    for(auto& i : values) {
        std::cout << i << std::endl;
    }
}
int main() {
    int* arr = new int[5]{0,1,2,3,4};
    func({arr,5});
}

Answered by Raildex on February 10, 2021

You can use C++ std::array:

#include <array>
#include <iostream>

void sortArray(std::array<int, 5> &arr)
{

    int count0s{0},count1s{0},count2s{0};
     for (int n: arr)
     {

     }

}
int main()
{
    std::array<int, 5> arr;
    sortArray(arr);
  
    return 0;
}

Or C++ std::vector:

#include <iostream>
#include <vector>

void sortArray(std::vector<int> &arr)
{

    int count0s{0},count1s{0},count2s{0};
     for (int n: arr)
     {

     }

}
int main()
{
    std::vector<int> arr;
    sortArray(arr);
  
    return 0;
}

Use a template to avoid a fixed size and type in the function:

#include <array>
#include <iostream>

template<typename T>
void sortArray(T &arr)
{
    int count0s{0},count1s{0},count2s{0};
    for (int n: arr)
    {
    }
}
int main()
{
    // it works with C arrays
    int arr[5];
    sortArray(arr);
    std::array<int, 5> arr2;
    sortArray(arr2);
    std::array<double, 5> arr3;
    sortArray(arr3);
    std::vector<double> arr4;
    sortArray(arr4);

    return 0;
}

With C++20 you can

#include <array>
#include <iostream>

void sortArray(auto &arr)
{
    int count0s{0},count1s{0},count2s{0};
    for (int n: arr)
    {
    }
}
int main()
{
    int arr[5];
    sortArray(arr);
    std::array<int, 5> arr2;
    sortArray(arr2);
    std::array<double, 5> arr3;
    sortArray(arr3);
    std::vector<double> arr4;
    sortArray(arr4);

    return 0;
}

Answered by Thomas Sablik on February 10, 2021

parameter int arr[/*N*/] is in fact a pointer, (you cannot pass C-array by value).

but you can pass it by reference (syntax might surprise):

template <std::size_t N>
void sortArray(int (&arr)[N])
{
    // ...
}

Answered by Jarod42 on February 10, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP