我有一个简单的结构体
叫做Item
。
struct Item {
unsigned int id;
std::string name;
Item() : id( 0 ), name( std::string( "" ) ) {
};
};
然后我有一个类来保存所有这些Item
。
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
)?
std::map
具有 O(log n) 的查找时间。 - Dark Falcon0
,1
,176
,2000
是一些有效的ID。 - alxcylname( std::string( "" ) )
是完全多余的。 - Lightness Races in Orbit