decltype

I have this question but I don't think I fully understood how to use decltype

1
2
3
4
5
6
7
8
9
10
11
map<int, float> m = build_map();
std::pair<int, int> scaling_factor(2, 3);
std::pair<int, int>* scaled_array = new std::pair<int, int>[m.size()];
int i(0);
for(map<int, float>::iterator it=m.begin(); it!=m.end(); it++, i++)
{
std::pair<int, int> tmp=*it;
tmp.first *= scaling_factor.first;
tmp.second *= scaling_factor.second;
scaled_array[i] = tmp;
}


Try to simplify the above code by finding a good place to use decltype.
Last edited on
Well it seems to me you'd be better off using "auto" rather than decltype here:
1
2
3
4
5
6
7
8
9
10
11
auto m = build_map();
std::pair<int, int> scaling_factor(2, 3);
auto* scaled_array = new std::pair<int, int>[m.size()];
int i(0);
for(auto it=m.begin(); it!=m.end(); it++, i++)
{
    auto tmp=*it;
    tmp.first *= scaling_factor.first;
    tmp.second *= scaling_factor.second;
    scaled_array[i] = tmp;
}


But if you have to use decltype, then this should suffice:
1
2
3
4
5
6
7
8
9
10
11
map<int, float> m = build_map();
std::pair<int, int> scaling_factor(2, 3);
decltype(scaling_factor)* scaled_array = new std::pair<int, int>[m.size()];
int i(0);
for(decltype(m)::iterator it=m.begin(); it!=m.end(); it++, i++)
{
decltype(scaling_factor) tmp=*it;
tmp.first *= scaling_factor.first;
tmp.second *= scaling_factor.second;
scaled_array[i] = tmp;
}


However doing so is completely ridiculous and provides no benefit whatsoever, at least in this context. It would be better to use auto.
Maybe this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
	using type = decltype(std::pair<int, int>());
	using ftype = decltype(map<int, float>());

	ftype m = {};
	type scaling_factor(2, 3);
	type* scaled_array = new type[m.size()];
	int i(0);
	for (ftype::iterator it = m.begin(); it != m.end(); it++, i++)
	{
		type tmp = *it;
		tmp.first *= scaling_factor.first;
		tmp.second *= scaling_factor.second;
		scaled_array[i] = tmp;
	}

Topic archived. No new replies allowed.