How to display the contents of a set in a loop?
- Output where? And what exactly is the difficulty? - αλεχολυτ
|
2 answers
for(auto i : set_object) cout << i << endl; :)
Type:
int main(int argc, const char * argv[]) { set<int> s = { 1,2,45,23,19,8}; for(auto i : s) cout << i << endl; } - oneGenerally -
const auto&- Abyx
|
You can use a regular for loop with iterators, or a range-based loop. You can also use standard algorithms such as, for example, std::copy or std::copy_if
Here are examples of output.
std::set<int> s{ 1, 2, 3, 4, 5 }; for (std::set<int>::iterator it = s.begin(); it != s.end(); ++it) { std::cout << *it << ' '; } std::cout << std::endl; for (const auto &item : s) std::cout << item << ' '; std::cout << std::endl; std::copy(s.begin(), s.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; std::copy_if(s.begin(), s.end(), std::ostream_iterator<int>(std::cout, " "), [](int x) { return x % 2 != 0; }); std::cout << std::endl; The output of these code fragments will be as follows.
1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 3 5 Iterator declaration in this loop
for (std::set<int>::iterator it = s.begin(); it != s.end(); ++it) can be simplified
for (auto it = s.begin(); it != s.end(); ++it) |