I have a structure that contains information about a geometrical figure. My problem is that I don\'t know to display the volume of figures that are unique (it means that another
sf[i].volume
access the volume field of the i-th element of your array of structures
For the algorithm to find unique values of volumes, it depends on your dataset.
The most generic approach would be to sort your array using 'volume' as key. When your array is sorted this way, it's easy to count the unique entries by just ignoring consecutive entries of the same value.
example:
'1 6 7 2 7 9 7' becomes '1 2 6 7 7 7 9' you strip away consecutive entries of same value or ignore them '1 2 6 7 9'. and you have a list of unique volume entries.
UPDATE:
@Max Langhof suggestion to use std::unique is cleaner. You only need to use std::vector to have iterators and lambda to specify the field you are working on.
#include
#include
#include
#include
int main()
{
typedef struct _Sfere
{
char codsf[5];
char colour[15];
char material[15];
float r,area,volume;
} Sfere;
//Encapsulate structure in a standard vector to have iterators
std::vector my_sfere_vector(10);
//Insert unique elements
my_sfere_vector[1].volume = 1.0;
my_sfere_vector[7].volume = 3.0;
//Show content
for (std::vector::iterator my_element = my_sfere_vector.begin();my_element != my_sfere_vector.end();my_element++)
{
std::cout << " " << my_element->volume;
}
std::cout << "\n";
//Sort the vector
std::sort
(
my_sfere_vector.begin(),
my_sfere_vector.end(),
[](const Sfere &a, const Sfere &b)
{
return a.volume < b.volume;
}
);
//Unique elements
std::vector::iterator last = std::unique
(
my_sfere_vector.begin(),
my_sfere_vector.end(),
[](const Sfere &a, const Sfere &b)
{
return a.volume == b.volume;
}
);
//Prune out excess elements
my_sfere_vector.erase(last, my_sfere_vector.end());
//Show content
for (std::vector::iterator my_element = my_sfere_vector.begin();my_element != my_sfere_vector.end();my_element++)
{
std::cout << " " << my_element->volume;
}
std::cout << "\n";
}
This is the result
0 1 0 0 0 0 0 3 0 0
0 1 3
Process returned 0 (0x0) execution time : 0.015 s
Press any key to continue.