如何在下一个函数调用中从最后一个位置使用STL映射擦除?

时间:2019-01-21 06:47:36

标签: c++ stl

我有此代码:

bool Sparse_Matrix_RL::removeColsFromRow(unsigned int row_id, std::list<unsigned int>& col_ids)
{
    std::list<unsigned int>::iterator c_str,s_str;
    std::list<unsigned int>::iterator c_end = col_ids.end();
    std::map<unsigned int, std::map<unsigned int, double> >::iterator m_str;
    if (data_Matrix.count(row_id)) 
    {
        m_str = data_Matrix.find(row_id);
    }
    else 
    {
        std::cout << "Row not found";
        return false;
    }
    std::map<unsigned int, std::map<unsigned int, double> >::iterator m_end = data_Matrix.end();
    std::map<unsigned int, std::map<unsigned int, double> >::iterator row;
    if (m_str != m_end)
    {
        for (c_str = col_ids.begin(); c_str != c_end; c_str++)//col_id's are sorted 
        {
            m_str->second.erase(*c_str);
        }
    }
    if (data_Matrix[row_id].size() == 0)
        data_Matrix[row_id][row_id] = 0;
    return true;
}

以下是我的函数调用:

list<unsigned int>::iterator direc_Str = direc_dofs_list.begin();
list<unsigned int>::iterator direc_End = direc_dofs_list.end();
list<unsigned int>::iterator p;
for (int rid = 0; rid < total_rows; rid++)
{
    p = std::find(direc_Str, direc_End, rid);
    if (p == direc_End)
        stiffness_matrix->removeColsFromRow(rid, direc_dofs_list);
}

我正在传递行ID和一个要起作用的列表。在功能上,首先我要在map中找到该行,然后才发现要擦除该行中的数据,同时给它列中的列。现在擦除功能找到该位置并将其擦除。我希望擦除功能每次擦除一个索引后就从下一个索引开始查找索引。我想这样做是为了加快速度。

1 个答案:

答案 0 :(得分:2)

由于col_ids已排序,因此您可以利用该顺序并简单地遍历列表并将其映射在一起,就像在合并排序的合并步骤中一样,并选择匹配的索引。

auto mm_itr = m_str->second.begin(), mm_end = m_str->second.end();
while(c_str != c_end && mm_itr != mm_end) {
  if(*c_str < mm_itr->first) // c_str smaller, progress it
    ++c_str;
  else if(*c_str > mm_itr->first) // key is smaller, progress it
    ++mm_itr;
  else {
    mm_itr = m_str->second.erase(mm_itr); // They are equal, erase and grab the returned iterator
    ++c_str; // Can also progress in the list now
  }
}