【发布时间】:2013-09-02 03:47:11
【问题描述】:
我有一个简单的struct,叫做Item。
struct Item {
unsigned int id;
std::string name;
Item() : id( 0 ), name( std::string( "" ) ) {
};
};
然后我有这个类来保存所有这些Items。
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。 -
name( std::string( "" ) )完全是多余的。 -
getItem很恶心。一方面,你正在重新发明轮子。std::find为您执行此操作,前提是您提供了一个仿函数(或 C++11 中的 lambda)。另一方面,getItem不只是获取项目。它找到它,然后替换它。简单胜于复杂。 -
@JohnDibling:“它取代了它”是什么意思?