Reputation: 707
I can pass my array directly, but I need to know how to pass it by reference. I'm using the new std::array with type Element. I've tried several things, but they're not working. I'm not sure how to pass it as a reference. I've messed around and I can't figure this out.
How do I pass a std::array as a reference parameter to avoid copying the entire array?
How my array is set up:
std::array<Element, 115> Elements =
{{
/*int aNumber, float awNumber, period_number PERIOD, group_names GROUP_NAME, metal_status METALSTATUS,
valence_shell Orbital,std::string eName, std::string eSybol);*/
{},
{1, 1.00794, period::PERIOD_ONE, group::HYDROGEN, metal::NONMETAL, shell::S_ORBITAL, "Hydrogen", "H"}
}};
Working
void sortByAtomicNumber(std::array<Element, 115> elements, int minimum, int maximum)
{
int counter = 1;
for(;minimum < (maximum+1); minimum++)
{
std::cout << counter << ".) " << elements[minimum].getElementName() << std::endl;
counter++;
}
}
Tried From: http://gauravpandey.com/wordpress/?p=602 //I haven't learned templates yet...
template<size_t N>
void sortByAtomicNumber(std::array<int, N> const& arr, int maximum, int minimum) {
int counter = 1;
for(;minimum < (maximum+1); minimum++)
{
std::cout << counter << ".) " << arr[minimum].getElementName() << std::endl;
counter++;
}
}
Error from Above
error: passing 'const value_type {aka const Element}' as 'this' argument of 'std::string > > Element::getElementName()' discards qualifiers [-fpermissive]
Upvotes: 5
Views: 15475
Reputation: 63
Your function definition looks wrong, the const is in the wrong place: You gave this definition:
template<size_t N>
void sortByAtomicNumber(std::array<int, N> const& arr, int maximum, int minimum)
{
...
}
It should be:
template<size_t N>
void sortByAtomicNumber(const std::array<int, N>& arr, int maximum, int minimum)
{
...
}
Upvotes: -2
Reputation: 736
You have some errors:
In the template sortByAtomicNumber
, std::array<int, N>
should be std::array<Element, N>
.
If you want call a function of a const object, the function must be const. So your arr
is const reference, the void getElementName();
of the Element
class should be void getElementName() const;
.
If you want call a non-const function of a object, the object must be non-const. So template<size_t N> void sortByAtomicNumber(std::array<int, N> const& arr, int maximum, int minimum) { /* your code */ }
should be template<size_t N> void sortByAtomicNumber(std::array<Element, N>& arr, int maximum, int minimum) { /* your code */ }
, like @portforwardpodcast said.
Note: About the const function of const class, you can see this article. Hope that can help you.
Upvotes: 2
Reputation: 7635
Try this:
void sortByAtomicNumber(std::array<Element, 115> &elements, int minimum, int maximum)
{
int counter = 1;
for(;minimum < (maximum+1); minimum++)
{
std::cout << counter << ".) " << elements[minimum].getElementName() << std::endl;
counter++;
}
}
Upvotes: 2