如何直接从输入流向set容器插入输入值?
std::set Nice goal—cutting out that extra temporary variable makes the code cleaner! The syntax you’re hoping for (while(n--) { cin>>s.emplace(); }) won’t compile directly though, because std::set::emplace() returns a std::pair<iterator, bool> and there’s no operator>> overload for that pair type in the standard library. Let’s walk through two solid alternatives that let you ditch the int x; line:
Solution 1: Write directly to the element created by emplace()
You can use the iterator returned by emplace() to write straight to the newly created element in the set:
while (n--) { std::cin >> *s.emplace().first; }
How this works:
s.emplace()(called without arguments) default-constructs anint(initially0) in the set and returns a pair:.firstis an iterator pointing to the element (either the new one, or an existing duplicate since sets don’t allow duplicates).secondis a boolean that tells you if the element was actually inserted
- Dereferencing the iterator gives a reference to the element in the set, which
std::cincan overwrite directly with the input value.
Note: This only works if your set’s element type supports default construction and has a valid operator>> (which int does out of the box). For custom types, you’ll need to make sure those requirements are met.
Solution 2: Use standard algorithms for a concise one-liner
If you prefer a more functional style, you can skip the manual loop entirely with standard library tools:
#include <iterator> #include <algorithm> // ... std::copy_n(std::istream_iterator<int>(std::cin), n, std::inserter(s, s.end()));
How this works:
std::istream_iterator<int>(std::cin)creates an iterator that readsints directly from the input streamstd::copy_ncopies exactlynelements from this input iterator to the insertion iteratorstd::inserter(s, s.end())handles adding each element to the set automatically (no temporary variable needed under the hood).
Both approaches eliminate the explicit temporary variable while keeping the code readable and correct.
内容的提问来源于stack exchange,提问作者Zeros

