C++ 从字符串创建散列并使用 lower_bound 将其存储在向量中

问题描述 投票:0回答:0

为了识别用户,我将创建一个散列,它也用于组织向量中的项目。 但是当我使用 del 方法时,没有任何内容被删除,我是 C++ 的初学者,所以我可能忽略了一些基本错误。预先感谢您的所有评论。完整程序https://onecompiler.com/cpp/3z3u4gpgg

    class CPerson
    {
      ...
    };
    
    CPerson::CPerson(const string &name, const string &surname, const string &email, unsigned int salary )
    :   ...
        m_ID(hash<string>{}(name+surname))
    {
    }
    
    bool CPerson::operator == (const CPerson &person) const
    {
       return m_ID == person.m_ID;
    }
    
    bool CPerson::operator < (const CPerson& person) const 
    {
        if (m_ID < person.m_ID )
            return 1;
        else if(m_ID > person.m_ID)
            return -1;
        
        return 0;
    }
class CPersonalAgenda
{
  ...
      vector<CPerson> m_Employees;
};

bool CPersonalAgenda::add ( const string &name, const string &surname, const string &email, unsigned int salary )
{
  CPerson newEmployee(name, surname, email, salary);
  auto it = lower_bound(m_Employees.begin(), m_Employees.end(), newEmployee);

  if(it == m_Employees.end())
  {
    m_Employees.insert(it, newEmployee);
    return true;
  }
  
  return false;
}

bool CPersonalAgenda::del( const string &name, const string &surname)
{
  auto it = lower_bound(m_Employees.begin(), m_Employees.end(), CPerson(name,surname,"",-1));
  
  if(it != m_Employees.end())
  {
    m_Employees.erase(m_Employees.begin() + distance(m_Employees.begin(), it));
    return true;
  }

  return false;
}

int main ( void )
{
  CPersonalAgenda db;
  db.add("Marek", "Hamsik", "[email protected]", 585000); 
  db.add("Tomas", "Rosicky", "[email protected]", 585000); 
  db.add("Antonin", "Barak", "[email protected]", 585000); 
  db.add("TomaS", "Rosicky", "[email protected]", 585000);

  db.del("Marek", "Hamsik");
}
c++ hash std lower-bound
© www.soinside.com 2019 - 2024. All rights reserved.