c++ - 在 C++ 中创建两个 vector 之间的链接

标签 c++ design-patterns vector

这是一个概念性问题,因此我没有提供“工作代码”。

假设一个人有两个不同类型和不同数量实体的 std::vector,例如:

vector <int> A;
vector <string> B;

一个人有一组规则,遵循这些规则可以将 A 的任何成员与 B 的一些(或没有)成员相关联。

有没有办法“存储”这个连接?

我在想这样做的方法之一是拥有一个 vector <map <int, vector <string> > >vector <map <int, vector <string*> > > ,但这个解决方案在我看来不可靠(例如,如果 A 包含两个相同的数字),我认为那里有更优雅的解决方案。

最佳答案

您可以实现一些数据库 技术:索引。将您的数据放入单个 vector,然后为您想要索引数据或关联数据的每种方式创建 std::map

不是 2 个 vector ,而是一个结构 vector :

struct Datum
{
  int value;
  string text;
};

// The database
std::vector<Datum> database;

// An index table by integer
std::map<int, // Key
         unsigned int vector_index> index_by_value;

// An index table, by text
std::map<std::string, // Key
         unsigned int index_into_vector> index_by text;

索引表为您提供了一种快速查找数据库中内容的方法,而无需对数据库进行排序。

关于c++ - 在 C++ 中创建两个 vector 之间的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40473360/

相关文章:

c# - 设计模式 : Which one to choose?

c++ - 添加到对 vector

c++ - 将指针分配添加到 vector 后删除它

c++ - 以下是等同于 C++ CLI 的 C# 代码

c++ - C++ 中的右值引用

c++ - 智能感知 : a value of type "void *" cannot be assigned to an entity of type "char *"

c++ - Eigen 和 std::vector

c# - 使用 Entity Framework 设计模式?

r - apply() 函数分别按顺序应用于矩阵的列和数值向量的元素

c# - 重构帮助c#