A easy problem for you guys! about const pointer, with code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <string>
#include <vector>
using namespace std;



/*template <typename aType>
inline aType* begin(const vector<aType> &vec) {
	return vec.empty()? 0: &vec[0];
}*/

template <typename aType>
aType* find1(const aType* first, const aType* last, const aType &value) {
	if(!first||!last) return 0;
	for( ;first!=last;++first) {
		if(*first==value) return first;
	}
	return 0;
}

int main() {
	int ia[8]={1,1,2,3,5,8,13,21};
	double da[6]={1.5,2.0,2.5,3.0,3.5,4.0};
	string sa[4]={"pooh", "piglet", "eeyore", "tigger"};

	cout << "pi=" << &ia<<endl;
	cout << "pd=" << &da<<endl;
	cout << "ps=" << &sa<<endl;

	int *pi=find1(ia,ia+8,ia[3]);
	double *pd=find1(da,da+6,da[3]);
	string *ps=find1(sa,sa+4,sa[3]);

	cout << "pi=" << &ia<<endl;
	cout << "pd=" << &da<<endl;
	cout << "ps=" << &sa<<endl;

	cout << "pi=" << pi<<endl;
	cout << "pd=" << pd<<endl;
	cout << "ps=" << ps<<endl;
	return 0;
}


I need to delete the "const" of "const aType *first" to debug through, but I can easily find that I didn't change any inputted address. What is the problem? Thanks!

Last edited on
Here:

return first;

You can't convert first to a pointer to a non-const object.
Thanks, I don't understand,
const aType *first, define an aType pointer which point to a const object, but this doesn't mean I cannot change the value of first itself.
Right?
Yeah. That part is correct. However, since first is:

const aType*

you can't return it since that would require converting it to:

aType*
Topic archived. No new replies allowed.