访问映射<整数,对<双精度,双精度>>元素

access to map<int,pair<double,double>> elements

本文关键字:gt lt 双精度 元素 整数 映射 访问      更新时间:2023-10-16

我已经通过一个函数传递了一个map<double, pair<int, int>>,现在我想访问这对中的元素,这是怎么可能的?我的问题如下:

void func(map<double ,pair<int ,int > & f)
{
  int d= b+c;
}

如果您确定a存在:

void func(int a,map<int,pair<double,double>>& m)
{
    double d = m[a].first + m[a].second;
}
否则

:

void func(int a,map<int,pair<double,double>>& m)
{
    double d = 0;
    if( m.find(a) != m.end() ) 
        d = m[a].first + m[a].second;
}

尝试使用:

void func(map<int, pair<double, double> >& m)
{
    for (auto i : m)
    {
        double d = i.second.first + i.second.second;
    }
}

另外,阅读关于映射、配对和模板的手册也会很有用。

以下可能会有所帮助(在c++ 11中):(https://ideone.com/WcFHaw)

void print(const std::map<int, std::pair<int, int>> &m)
{
    for (const auto& p : m)
    {
        std::cout << "key = " << p.first << ", value = {" << p.second.first << ", " << p.second.second << "}"<< std::endl;
    }
}