我有这个简单的struct
,调用了Item
。从std :: vector获取特定结构对象的快速方法
struct Item {
unsigned int id;
std::string name;
Item() : id(0), name(std::string("")) {
};
};
然后,我有这个类来容纳所有这些Item
s。
class ItemData {
public:
std::vector<Item> m_Items;
private:
void load() {
// Parse a JSON string to fill up m_Items vector with
// Item objects.
}
const Item getItem(unsigned int pID) {
// Create an "empty" Item object with ID = 0 and name = ""
Item temp = Item();
// Loop through the vector
for (unsigned int i = 0; i < m_Items.size(); i++) {
// Check if the current Item object has the id we are looking for
if (m_Items.at(i).id == pID) {
// The item is inside the vector, replace temp with the
// target vector
temp = m_Items.at(i);
// Stop looping
break;
}
}
// If pID was found, temp will have the values of the object inside the vector
// If not, temp will have id = 0 and name = ""
return temp;
}
};
我觉得这个方法需要太多的时间,特别是如果ItemData::getItem(unsigned int)
在一个循环中调用。
是否有一种更有效的方式获取矢量内的对象,而无需通过矢量循环?我应该使用不同的容器(例如std::list
)吗?
什么是您的ID的一些例子?关于不同的容器,'std :: map'具有O(log n)查找时间。 –
@DarkFalcon ID是简单的无符号整数。 '0','1','176','2000'是一些有效的ID。 – alxcyl
'name(std :: string(“”))'完全是多余的。 –