我有这个简单的struct
叫Item
.
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
例如)吗?