You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何直接从输入流向set容器插入输入值?

How to Skip the Temporary Variable When Inserting Input Stream Data into a 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 an int (initially 0) in the set and returns a pair:
    • .first is an iterator pointing to the element (either the new one, or an existing duplicate since sets don’t allow duplicates)
    • .second is 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::cin can 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 reads ints directly from the input stream
  • std::copy_n copies exactly n elements from this input iterator to the insertion iterator
  • std::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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 23:42:41