Reputation: 42
I am just learning c++ and am attempting to understand arrays.. So forgive my ignorance on what's wrong here.
#include <iostream>
#include <string>
#include <array>
using namespace std;
void readArray(int *readfile, int ArraySize){
int Interator;
for(Interator = 1; Interator < ArraySize; Interator++){
cout << " " << readfile[Interator];
}
}
int main(){
std::array<int, 5> array2={{1, 2, 3, 4, 5}};
readArray(array2, array2.end());
}
Error: Can't Convert 'std::array' to 'int*' for arg '1'to void 'readArray'
How would I fix this?
Upvotes: 0
Views: 3479
Reputation: 1181
You cannot convert std::array
to int*
as compiler says. For such conversion you can use plain old array:
void readArray(int *readfile, int ArraySize)
{
int Interator;
for(Interator = 0; Interator < ArraySize; Interator++)
{
cout << " " << readfile[Interator];
}
}
int main()
{
//std::array<int, 5> array2={{1, 2, 3, 4, 5}};
int array2[] = {1, 2, 3, 4, 5};
readArray(array2, 5);
}
Also, Interator
is changed to start from zero. If you need std::array
then use std::array::begin()
and std::array::begin()
:
void readArray2(const std::array<int, 5>& a)
{
for (auto elem : a)
cout << " " << elem;
}
int main()
{
std::array<int, 5> array2={{1, 2, 3, 4, 5}};
//int array2[] = {1, 2, 3, 4, 5};
readArray2(array2);
}
Upvotes: 2
Reputation: 133567
Just browse some reference to discover that std::array
has a T* data()
and a constexpr size_type size()
which can and should be used for that purpose.
But this is a poor solution. The best solution would be to use iterators directly, eg:
template <typename T> void readArray(const T& data) {
for (const auto& element : data)
cout << element;
}
std::array<int, 5> data1 = { 1, 2, 3, 4, 5};
readArray(data1);
std::vector<int> data2 = {1, 2, 3, 4, 5};
readArray(data2);
std::list<int> data3 = {1, 2, 3, 4, 5};
readArray(data3);
Which would expect T
to be a type that has proper begin
and end()
overloads.
It makes no sense to tag questions with C++11 if you try to use C solutions,
Upvotes: 3