gpt4 book ai didi

C++ map 比较

转载 作者:行者123 更新时间:2023-11-28 05:58:42 28 4
gpt4 key购买 nike

早上好,我无法以正确的方式使用 map 。

情况

具有唯一 ID 和其他两个代码的数据库表

ID (long) | Type (long) | Name (string)

为了正确填充 map ,我用这种方式定义了它:

map<long, MyObject>

其中 key 是我的 ID,对象包含所有内容。 map 工作正常,我加载了所有行并在其中轻松导航。

麻烦

当我需要使用不是关键的标准对行进行排序时,问题就来了:

  1. 类型
  2. 姓名

环顾互联网,我发现我应该:

  1. 为 MyObject 或...定义运算符
  2. 为我的 map 定义另一种类型的比较器。

我执行了第 1 步,但没有成功(从未调用过)。我正在尝试执行第 2 点,但收效甚微。我将粘贴一些代码来提供帮助:

class CSitoWebRigaVariante
{
public:
bool m_bSriDelete;
bool m_bSriVisibile;
long m_lSriId;
long m_lSriIdTipol;
long m_lSriCodGes;
CString m_strSriCodMat;
public:
CSitoWebRigaVariante(void);
CSitoWebRigaVariante(const CSitoWebRigaVariante& cRiga);
~CSitoWebRigaVariante(void);
bool operator<(const CSitoWebRigaVariante& cRiga);
void operator=(const CSitoWebRigaVariante& cRiga);
void Azzera(void);
static void CaricaDaMDB(CDB* pDB, long lIdVM, map<long, CSitoWebRigaVariante>& cRighe);
};
typedef map<long, CSitoWebRigaVariante> CSWRighe;

///> Static method to fill a map.
void CSitoWebRigaVariante::CaricaDaMDB(CADODatabase* pDB, long lIdVM, map<long, CSitoWebRigaVariante>& cRighe)
{
BOOL bValRit;
CRecordset* pRS;
CSitoWebRigaVariante riga;
CString strInt;

pRS = new CADORecordset(pDB);
strInt.Format(_T("SELECT * FROM SITOWEB_RIVARMAT WHERE sri_idvarmat = %ld;"), lIdVM);
cRighe.clear();
if (pRS->Open(strInt, CADORecordset::openQuery) == TRUE && pRS->GetRecordCount() > 0)
{
while (pRS->IsEOF() == FALSE)
{
bValRit = pRS->GetFieldValue(_T("sri_id"), riga.m_lSriId);
bValRit &= pRS->GetFieldValue(_T("sri_idtipol"), riga.m_lSriIdTipol);
bValRit &= pRS->GetFieldValue(_T("sri_codges"), riga.m_lSriCodGes);
bValRit &= pRS->GetFieldValue(_T("sri_codmat"), riga.m_strSriCodMat);
bValRit &= pRS->GetFieldValue(_T("sri_delete"), riga.m_bSriDelete);
bValRit &= pRS->GetFieldValue(_T("sri_visibile"), riga.m_bSriVisibile);
cRighe.insert(pair<long, CSitoWebRigaVariante>(riga.m_lSriCodGes, riga));
pRS->MoveNext();
}
}
pRS->Close();
delete pRS;
}

我正在使用 Visual Studio 2010、MFC。感谢您的帮助。

最佳答案

std::map 不是多索引关联容器。它的 find 方法(和其他东西)使用键作为搜索条件。无法指定其他搜索条件。这就是为什么它是一个“单索引查找表”。

您可以使用 Boost.MultiIndex .它专为您的情况而设计,支持多个索引(顾名思义),既有唯一的也有非唯一的。

或者您可以使用具有不同键的多个 map 实例。如果键不是唯一的,则需要 std::multimap

关于C++ map 比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33690597/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com