【发布时间】:2015-03-26 21:13:27
【问题描述】:
我有一个人的结构类。每个人都有自己的姓名、主要 ID 和次要 ID。为了有效搜索,我实现了二进制搜索。问题是我想有效地(比 O(n) 更好)搜索人不仅通过他们的主要 ID,而且通过他们的次要 ID。但是这些人只能按一个参数排序。所以我想是否有可能制作两个指向persons结构的指针向量,一个按主ID排序,另一个按次要ID排序。
例如,两个人:Mark Smith 的主 ID 为 9845613,辅助 ID 为 1312469,John Doyle,主 ID 为 3213444,辅助 ID 为 2654722。所以 m_byPrim 向量的第一个元素和 m_bySec 向量的第二个元素应该指向 John Doyle。
这可能吗?以下是我目前编写的相关代码的一部分:
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <string>
using namespace std;
class CPersons
{
public:
bool AddPerson (const string &name,
unsigned int primID,
unsigned int secID);
private:
struct Person {
Person (const string & init_name,
unsigned int init_primID,
unsigned int init_secID)
: m_name (init_name), m_primID (init_primID), m_secID (init_secID){}
string m_name;
unsigned int m_primID;
unsigned int m_secID;
};
vector<Person*>m_byPrim;
vector<Person*>m_bySec;
};
bool CPersons::AddPerson (const string &name,
unsigned int primID,
unsigned int secID){
int positionPrim;
int positionSec;
return false;
}
int main ( void )
{
CPersons a;
a.AddPerson ( "Mark Smith", 9845613, 1324697 );
a.AddPerson ( "John Doyle", 3213444, 2654722 );
return 0;
}
位置整数是我的二进制搜索函数的结果(插入人员的位置),我已经成功地实现了它,所以假设这个位置已经被初始化了。
但我的问题是如何实现指针向量的添加?我对指针(以及一般的 C++)仍然很陌生,所以我不知道我的想法是否有效和可能。感谢您提供任何提示和帮助。
编辑:我忘了提到在 STL 容器中我只能使用向量。
【问题讨论】:
-
您问:“这可能吗?”。是的,这是可能的。请参阅std::sort 以开始使用。
-
您所做的与关系数据库在索引不同列时所做的类似。我认为您应该能够在向量上使用
insert将指针放在您需要的位置,但是您可能会从更复杂的结构中获得更好的结果来保存您的排序指针,例如树形图。 -
boost::multi_index 可能会有所帮助。
标签: c++ sorting pointers vector structure