【问题标题】:std::map insertion without creating a temporary valuestd::map 插入而不创建临时值
【发布时间】:2013-04-17 17:19:46
【问题描述】:

我有一个存储、字符串和一组双精度的地图,如下所示。

typedef std::map<std::string, std::set<double> > exprType;
typedef std::map<std::string, std::set<double> >::iterator exprIter;

exprType exPricesData;

std::vector<double> lastprice;
std::string exchange;

我需要一种为给定键插入价格的方法,并编写了以下代码。

  std::set<double> prices;
  double temp =  lastprice[0]; // An array of values comes as a parameter
  prices.insert(temp); // Creating a temp. set

  std::pair<exprIter,bool> locIter = exPricesData.insert(
            std::pair<std::string, std::set<double> >(exchange, prices));

   for ( int i = 1; i < lastprice.size() ; ++i )
   {
        locIter.first->second.insert(lastprice[i]);
   }

我想知道,有没有办法特别改进第一部分,它创建了一个临时集。

【问题讨论】:

  • 我删除了我的答案,因为我误读了您的代码。你可以插入一个空集std::pair&lt;exprIter,bool&gt; locIter = exPricesData.insert(std::pair&lt;std::string, std::set&lt;double&gt; &gt;(exchange, std::set&lt;double&gt;()));

标签: c++ stl stdmap stdset


【解决方案1】:

你的意思是这样的吗?

std::set<double> &prices = exPricesData[exchange];  //returns existing value, or inserts a new one if key is not yet in map

prices.insert(lastprice.begin(), lastprice.end());

哦,使用std::set&lt;double&gt; 时要小心。如果数字是计算的结果,则数字不准确可能会导致集合中的不同成员出现在您不期望的地方。

【讨论】:

  • 显然,当我添加我的答案时,这个问题并没有刷新说这个答案就在那里。将删除我的并为你 +1 好先生。
  • @pstrjds 谢谢。有时“新答案”弹出窗口确实很慢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-25
  • 1970-01-01
  • 2010-09-10
  • 1970-01-01
  • 2019-08-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多