C++容器存储(insert/get/remove)结构,具有整数值的多键是指针

C++ container to store(insert/get/remove) structure with multi key of integer value is pointer

本文关键字:整数 指针 结构 存储 insert remove get C++      更新时间:2023-10-16

如何存储以下结构密钥=[k1,k2,…,kn];值=无效*n在编译时是未知的。它对于对象是常量,但对于类是可变的。它必须像树,但是C++STL。它必须尽可能快地插入、移除和获取。我认为它一定是map[inter,map[interer,…map[interger,void*]…]]但我不明白如何在未知级别"n"的情况下实现它。

它用于"队列",其中项目可以按未知顺序插入,但必须按正确的顺序退出队列1,1,1,然后1,1,2。。。。1,1,V3max,1,2,1。。。

您可以创建这样一个简单的结构:

struct MyType
{
  std::string name;
  std::map<int, MyType> mA;
};

然后创建一个根映射,接受由密钥标识的MyType

std::map<int, MyType> mRootMap;

然后你可以像这样添加(为了简单,没有递归性)

MyType a;
MyType b;
MyType c;
c.name = "This is C";
b.mA[789] = c;
a.mA[456] = b;
mRootMap[123] = a; 

然后你可以像这样访问

std::cout << mRootMap[123].mA[456].mA[789].name << std::endl;

输出:

This is C

您可以将std::vector<int>operator<operator==一起用作密钥。

bool operator<(const std::vector<int>& a, const std::vector<int>& b)
{
    if (a.size() != b.size())
    {
        // decide what to do
    }
    for (std::vector<int>::size_type index = 0 ; index < a.size() ; ++index)
    {
        if (a[index] < b[index])
        {
            return true;
        }
    }
    return false;
}
bool operator==(const std::vector<int>& a, const std::vector<int>& b)
{
    // ...
}