尝试访问地图

时间:2018-03-24 22:17:43

标签: c++

这是我的.h文件,其中包含我正在创建的结构。

struct Market{
  string file_name;
  vector<string> symbol_list={"AA","AXP","BA","BAC","CAT","CSCO","CVX","DD",
                 "DIS","GE","HD","HPQ","IBM","INTC","JNJ","JPM",
                 "KFT","KO","MCD","MMM","MRK","MSFT","PFE",
                 "PG","T","TRV","UTX","VZ","WMT","XOM"};
  map<long, vector<double>> stocks;

  Market()=default;
  Market(string s);

  double get_price(string, long) const;
  pair<double, double> high_low_year(long year, string symbol);
};

#endif

我正在尝试创建get_price方法。它将获取输入的字符串并确保它是symbol_list的元素,并找到它的索引。我将使用此索引在地图中查找名为“stocks”的相应元素。

当我使用任何类型的索引技术或find函数时,我会收到错误。由于get_price是一个const方法,我已经发现我不能使用[]索引,因为如果密钥不存在,这将改变映射。 find函数也给了我疯狂的错误。这是我尝试的一种方式:

double Market::get_price(string stock, long date) const{
  //vector<string>::const_iterator stock_exist;
  //map<long, vector<double>>::const_iterator date_exist;
  auto stock_exist = find(symbol_list.begin(), symbol_list.end(), stock);
  auto date_exist = find(stocks.begin(), stocks.end(), date);
  if (stock_exist != symbol_list.end() and date_exist != stocks.end()){
    double stock_index = (stock_exist) - symbol_list.begin();
    double price = stocks.find(date)->second[stock_index];
    return price;
  }
  else{
    return -1.0;
  }
}

产生此错误:

/usr/include/c++/6/bits/predefined_ops.h:199:17: error: no match for ‘operator==’ (operand types are ‘const std::pair<const long int, std::vector<double> >’ and ‘const long int’)
  { return *__it == _M_value; }
           ~~~~~~^~~~~~~~~~~

我怎样才能解决这个问题?

1 个答案:

答案 0 :(得分:0)

你应该使用......

auto date_exist = stocks.find(date);

......而不是......

auto date_exist = find(stocks.begin(), stocks.end(), date);

那是因为std::map有自己的find成员函数,它将使用最佳二进制搜索。

您尝试使用的find - <algorithm>的非会员find - 将无法执行您想要的操作:它会搜索与地图条目“{{匹配的匹配项1}},即value_type - 您不希望在搜索时指定预期的std::pair<const long, vector<double>>。它的用法如下:

vector