0

I have a map like typedef map<int32_t,std::vector<int32_t>> myMap

I have added a value in vector with respect to the key like

myMap[somePointer->getVal()].push_back(Id1);
myMap[somePointer->getVal()].push_back(Id2);
myMap[somePointer->getVal()].push_back(Id3);
myMap[somePointer->getVal()].push_back(Id4);

What if I want to delete a value from the vector for the key? I tried doing myMap[somePointer->getVal()].erase(Id1)

But with this compiler cries with errors.

4

4 回答 4

1

试试这个删除第x+1th 元素

myMap[somePointer->getVal()].erase (myMap[somePointer->getVal()].begin()+x);

于 2013-09-25T12:54:08.487 回答
0

文档中,概要是:

C++98:

iterator erase (iterator position);
iterator erase (iterator first, iterator last);

C++11:

iterator erase (const_iterator position);
iterator erase (const_iterator first, const_iterator last);

所以你必须给一个迭代器。

it = myMap[somePointer->getVal()].begin() + index;
myMap[somePointer->getVal()].erase(it)

您也可以尝试使用multimap它。

于 2013-09-25T12:54:13.470 回答
0

向量不是为查找而设计的,因此接口不是基于值的。如果要从矢量中删除,则需要知道位置。好消息是您可以使用标准算法获取位置。相当于您的代码将是:

auto& vector = myMap[somePointer->getVal()];
auto it = std::find(vector.begin(), vector.end(), Id1);
if (it != vector.end()) { vector.erase(it); }

如您所见,它比您的原始版本更长且更复杂。如果你有元素在向量中的位置(即如果你知道你想删除第一个/最后一个/第 n 个元素),你可以用,和迭代器算术代替std::find正确的迭代器。begin()end()

于 2013-09-25T13:03:52.183 回答
0

对于 C++98 或 C++11,erase具有三种重载格式

C+98

void erase (iterator position);
size_type erase (const key_type& k);
void erase (iterator first, iterator last);

C++11

iterator  erase (const_iterator position);
size_type erase (const key_type& k);
iterator  erase (const_iterator first, const_iterator last);

所以你应该使用如下的第二种格式来删除

myMap.erase(somePointer->getVal()); // getVal() must return a type convertible to maps key_type

代替

myMap[somePointer->getVal()].erase(Id1)
于 2013-09-25T13:04:01.737 回答