How can I find the n smallest number of a set of numbers

Hey guys,
I have this doubt for a while
I'd like to know how i find the n smallest number of a set of number and not the smallest number.
For example:
I have this number in the enter: 54621
So, i'd like to know the three smallest number

- I appreciate any help!

If you store the elements in a std::set you just need to iterate the first n numbers because the elements are store in order smallest to largest.

If you store the elements in a vector or similar you can use std::partial_sort to sort so that the n smallest elements are first.
http://www.cplusplus.com/reference/algorithm/partial_sort/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <vector>
#include <algorithm> 

int main()
{
	const int n = 3;
	
	std::vector<int> v = {5, 4, 6, 2, 1};
	
	std::partial_sort(v.begin(), v.begin() + n, v.end());
	
	auto begin = v.begin();
	auto end = v.begin() + n;
	for (auto it = begin; it != end; ++it)
	{
		std::cout << *it << std::endl;
	}
}
Topic archived. No new replies allowed.