C++ 如何从向量中删除元素<;共享\u ptr>;
我正在使用以下代码构建一种注册表类:C++ 如何从向量中删除元素<;共享\u ptr>;,c++,vector,shared-ptr,C++,Vector,Shared Ptr,我正在使用以下代码构建一种注册表类: class MyClass { public: int a; std::string b; }; class Register { public: std::vector<std::shared_ptr<MyClass>> items; bool registerItem(std::shared_ptr<MyClass> item)
class MyClass
{
public:
int a;
std::string b;
};
class Register
{
public:
std::vector<std::shared_ptr<MyClass>> items;
bool registerItem(std::shared_ptr<MyClass> item)
{
/*
* Check if item exists
*/
auto position = std::find(items.begin(), items.end(), item);
if (position != items.end())
return false;
items.push_back(item);
return true;
}
bool unregisterItem(std::shared_ptr<MyClass> item)
{
auto position = std::find(items.begin(), items.end(), item);
if (position == items.end())
return false;
items.erase(item);
return true;
}
};
int main()
{
std::shared_ptr<MyClass> item1 = new MyClass;
Register registry;
if (!registry.registerItem(item1))
std::cout << "Error registering item1" << std::endl;
else
std::cout << "Success registering item1" << std::endl;
if (!registry.registerItem(item1))
std::cout << "Error unregistering item1" << std::endl;
else
std::cout << "Success unregistering item1" << std::endl;
}
class-MyClass
{
公众:
INTA;
std::字符串b;
};
类寄存器
{
公众:
向量项;
bool注册表项(std::shared\u ptr项)
{
/*
*检查项目是否存在
*/
自动定位=std::find(items.begin(),items.end(),item);
if(position!=items.end())
返回false;
项目。推回(项目);
返回true;
}
bool取消注册项目(标准::共享项目)
{
自动定位=std::find(items.begin(),items.end(),item);
if(position==items.end())
返回false;
项目。删除(项目);
返回true;
}
};
int main()
{
std::shared_ptr item1=新MyClass;
登记处;
如果(!registry.registerItem(item1))
std::cout有两种声明可用:
您尝试std::vector::erase
项目本身而不是迭代器。使用
items.erase(position);
相反。有两种声明可用:
您尝试std::vector::erase
项目本身而不是迭代器。使用
items.erase(position);
相反。因为您想在项中使用迭代器(即位置
),所以:
因为您想使用迭代器进入项
(即位置
),所以:
您必须在位置
上调用擦除
,而不是项目
由于擦除在迭代器上使用您必须在位置
上调用擦除
,而不是项
由于erase用于迭代器您应该传递给erase迭代器而不是一个值,因此删除std::shared_ptr没有什么特殊之处。此外,您的代码输入错误:您注册了两次项,而不是在第二次调用中注销它。您应该传递给erase迭代器而不是一个值,删除std::shared_ptr没有什么特殊之处tr.代码输入错误:在第二次调用中注册项两次,而不是注销它。删除的是迭代器,而不是值本身。在注册表中使用向量可能会很昂贵;如前所述,注册N个项需要O(N^2)
time。另一方面,内部循环速度快,存储开销最小。但是,如果您希望N
很大,您可能需要考虑一个std::unordered\u集
。您删除的是迭代器,而不是值本身。为注册表使用向量可能会很昂贵;按照说明,注册N个项需要e> O(N^2)
时间。另一方面,内部循环速度快,存储开销最小。不过,如果您希望N
很大,您可能需要考虑一个std::unordered\u set
。谢谢。这是我第一次使用擦除。谢谢。这是我第一次使用擦除。
items.erase(position);