I am new in C .I am using STL Containers.I am mapping the AnimalWeightCAT to unique values of distance travel in km.Using this code
#include <iostream>
#include <map>
#include <sstream>
int main() {
std::istringstream file(
"3 138 3 239 3 440 3 241 3 462 3 432 3 404 2 435 2 514 2 565 3 328 3 "
"138 5 401 5 142 5 404 5 460 5 472 2 418 5 510 2");
// some typedefs to make it simpler:
typedef int AnimalWeightCAT_t;
typedef int distance_t;
typedef int count_t;
typedef std::map<distance_t, count_t> distcount_t;
typedef std::map<AnimalWeightCAT_t, distcount_t> AWeightDistance;
AWeightDistance AWeightDistanceCount; // map AnimalWeightCAT -> distances with counts
AnimalWeightCAT_t AnimalWeightCAT; // temporary variable to read a AnimalWeightCAT
distance_t dist; // temporary variable to read a distance
// read AnimalWeightCAT and distance until the file is depleated and use AnimalWeightCAT and dist as
// keys in the outer and inner map and increase the count:
while (file >> AnimalWeightCAT >> dist) AWeightDistanceCount[AnimalWeightCAT][dist];
for(AWeightDistance::iterator adit= AWeightDistanceCount.begin(); adit!= AWeightDistanceCount.end(); adit) {
std::cout << "AnimalWeightCAT: " << adit->first << '\n';
for(distcount_t::iterator dcit = adit->second.begin();dcit != adit->second.end(); dcit){
std::cout << '\t' << dcit->first << ' ' << dcit->second << '\n';
}
}
}
How i can find the count of number of distict in indices of AnimalWeightCAT of iterator adit
by using map in C ?
Above code display the following output
Output:
AnimalWeightCAT: 2
418 1
435 1
514 1
565 1
AnimalWeightCAT: 3
138 2
239 1
241 1
328 1
404 1
432 1
440 1
462 1
AnimalWeightCAT: 5
142 1
401 1
404 1
460 1
472 1
510 1
I want this kind of output.How?
AnimalWeightCAT: 2 count = 4
AnimalWeightCAT: 3 count = 8
AnimalWeightCAT: 5 count = 6
CodePudding user response:
For count of the second map adit->second.size()
will be sufficient so your last loop, in order to look like you desire must be:
for(AWeightDistance::iterator adit = AWeightDistanceCount.begin();
adit != AWeightDistanceCount.end(); adit)
{
std::cout << "AnimalWeightCAT: " << adit->first
<< " count: " << adit->second.size() << '\n';
}
or simpler, using a range based for-loop:
for(auto&&[awc, dist_count] : AWeightDistanceCount) {
std::cout << "AnimalWeightCAT: " << awc
<< " count: "<< dist_count.size() << '\n';
}