这是一个概念性问题,因此我没有提供“工作代码”。
假设一个人有两个不同类型和不同数量实体的 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/