简体   繁体   中英

How to remove the vector object from the map

I have a map std::map<int, std::vector<Data>>myMap and my structure is defined as follows.

        struct Data
        {
         int x;
         int z;
         int y;
        };

in myMap key is int and value is vector of structure

I'm given with x and key value. I want remove the object from the vector where the key and x value of the vector object matches

I have tried by giving all the x,y,z values of the structure:

myMap[123].erase(std::remove(myMap[123].begin(), myMap[123].end(), {1,2,3}), myMap[priority].end());

But Here only X value will be given.

I have tried to write a function as follows:

void deleteByx(int x)
{
        for (std::map<int,std::vector<Data>>::iterator it = myMap.begin(); it != myMap.end(); it++)
        {
            std::vector<Data> list = it->second;
            for (std::vector<Data>::iterator vec_it = list.begin(); vec_it != list.end(); vec_it++)

            for(int index = 0;index < list.size();index++)
            {
                if (vec_it->x == x)
                {
                    list.erase(vec_it);
                }
            }


        }
}

but here the function deletes the element from the local vector list

If you want to have access to the actual data item, then you need to get a reference to that item. Instead, your current code gets a copy of the vector.

Thus this line:

std::vector<Data> list = it->second;

Should be:

std::vector<Data>& list = it->second;

Thanks for the time. I have tried with the following code and it worked for me.

for ( itr = myMap[key].begin(); itr != myMap[key].end(); ++itr)
    {
        if (itr->x == 1)
        {
            myMap[key].erase(itr);
            break;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM