Reputation: 43
I am writing up a function definition to let the user input elements of the array but get the error with cin >> a[index];
void show(const double a[], unsigned els) {
size_t index = 0;
for (index = 0; index < els; index++) {
cin >> a[index];
}
for (index = 0; index < els; index++) {
if (a[index] == a[0]) {
cout << "{" << a[index] << ",";
}
else if (a[index] == a[els - 1]) {
cout << a[index] << "}";
}
else { cout << a[index] << ","; }
}
cout << endl;
}
Upvotes: 2
Views: 247
Reputation: 62
Remember that with C++ passing parameters using []
operator is misleading; in fact this operator is defined on pointers. So what it is really happening in function show()
is to receive the pointer of the first element of the array passed. Passing this pointer as const
you cannot change the value pointed by the pointer, you can only apply the aritmetic rules of pointer (such as ++, assignment, subtraction...).
A possible solution could be:
void show(double *a, unsigned els) {
size_t index = 0;
for (index = 0; index < els; index++) {
cin >> a[index]; //that is the same of --> cin >> *(a + index)
}
for (index = 0; index < els; index++) {
if (a[index] == a[0]) {
cout << "{" << a[index] << ",";
}
else if (a[index] == a[els - 1]) {
cout << a[index] << "}";
}
else { cout << a[index] << ","; }
}
cout << endl;
}
I tested this code and it works. So the operator >>
exists for double
operands.
Optimization:
Note that if you want to create generic programming functions you should pass to the function the pointer of the first and the last element (despite the number of element i.e els
) of a container (array, list, vector...) and you scan your container in this way:
while (first != last) {
//your code ...
}
This is the same style of Alxander Stepanov, the creator of the STL.
Upvotes: 1
Reputation: 4770
See my comments in your copied code:
void show(const double a[], unsigned els) { // a is const
size_t index = 0;
for (index = 0; index < els; index++) {
cin >> a[index]; // you're trying to write to a const array
}
Upvotes: 7