How to delete the selected random data in std::vector?

Viewed 90

How to delete the selected random data in vector?

#include <iostream>
#include <vector>

int main()
{
    std::vector<int> shuf{ 1, 2, 3, 4, 5 };
    int random = shuf[rand() % shuf.size()];
    std::cout << random; // to get the random data in shu
    std::find(shuf.begin(), shuf.end(), random);
    shuf.erase(random);

    for (int k = 0; k < shuf.size(); k++)
    {
        std::cout << shuf.at(k) << ' ';
        break;
    }
}

For example data in shuf vector is { 1, 2, 3, 4, 5 } then the random data for example is 4 so that the 4 will be deleted in vector, so the data in vector will be shuf{ 1,2,3,5 }

This is the error I got

no matching function for call to 
'find(std::vector<int>::iterator, std::vector<int>::iterator, int&)'
1 Answers

At this like

shuf.erase(random);

you are passing a random of type int to the std::vector::erase, and do not make use of the result of std::find(shuf.begin(), shuf.end(), random);.

The std::vector::erase expect the valid iterator pointing to the element to be removed, not the actual element. Hence, the error.

From cppreference.com, the std::vector::erase needs

Parameters

pos - iterator to the element to remove. The iterator pos must be valid and dereferenceable. Thus the end() iterator (which is valid, but is not dereferenceable) cannot be used as a value for pos.

Therefore, you might want the following:

#include <algorithm> // std::find

auto iter = std::find(shuf.begin(), shuf.end(), random);
if (iter != shuf.end())
    shuf.erase(iter);

(See a Demo)

Note that you need to include <algorithm> (also other required) headers for compiler to see the algorithm function std::find.

Related