I want to print only first 10 inserted items while leaving the rest behind. What code do i have to use (instead of using myset.end()
) to print only first 10 integers instead of printing every single integer.
int main ()
{
std::set<int> myset;
std::set<int>::iterator it;
// set some initial values:
for (int i=1; i<=20; ++i)
myset.insert(i*10);
std::cout << "myset contains:";
for (it=myset.begin(); it!=myset.end(); ++it)
std::cout << *it << ' ';
std::cout << "\n\n";
return 0;
}
You might use std::next
as follow:
const auto begin = myset.begin();
const auto end = myset.size() < 10 ? myset.end() : std::next(begin, 10);
for (auto it = begin; it != end; ++it) {
std::cout << *it << ' ';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With