How to find the index of smallest 3 elements in an array
-
How can we find the index of smallest 3 elements in an array. Below code finds the index of largest 3 elements in an array.
#include #include using namespace std;
int main()
{
double arr[] = {0.2, 1.0, 0.01, 3.0, 0.002, -1.0, -20};priority_queue < pair > pQueue;
for (int i = 0; i < 7; i++)
{
pQueue.push(pair(arr[i], i));
}int k = 3; // number of indices we need
for (int i = 0; i < k; ++i)
{
int ki = pQueue.top().second;
cout << ki << " ";
pQueue.pop();
}}
-
How can we find the index of smallest 3 elements in an array. Below code finds the index of largest 3 elements in an array.
#include #include using namespace std;
int main()
{
double arr[] = {0.2, 1.0, 0.01, 3.0, 0.002, -1.0, -20};priority_queue < pair > pQueue;
for (int i = 0; i < 7; i++)
{
pQueue.push(pair(arr[i], i));
}int k = 3; // number of indices we need
for (int i = 0; i < k; ++i)
{
int ki = pQueue.top().second;
cout << ki << " ";
pQueue.pop();
}}
See std::priority_queue - cppreference.com[^]:
Quote:
A user-provided Compare can be supplied to change the ordering, e.g. using std::greater would cause the smallest element to appear as the top().
Another solution would be inverting the sign of the items pushed into the queue:
pQueue.push(pair(-arr[i], i));
-
See std::priority_queue - cppreference.com[^]:
Quote:
A user-provided Compare can be supplied to change the ordering, e.g. using std::greater would cause the smallest element to appear as the top().
Another solution would be inverting the sign of the items pushed into the queue:
pQueue.push(pair(-arr[i], i));
-
See the link from my answer. It contains example code showing that it must be passed as 3rd template parameter. So you have to pass also the 2nd parameter. As with any templates,
T
(uppercase) is a placeholder for the corresponding type which isstd::pair
in your case. So it must be (untested):priority_queue < pair, vector>, greater> > pQueue;
-
See the link from my answer. It contains example code showing that it must be passed as 3rd template parameter. So you have to pass also the 2nd parameter. As with any templates,
T
(uppercase) is a placeholder for the corresponding type which isstd::pair
in your case. So it must be (untested):priority_queue < pair, vector>, greater> > pQueue;