0

I have a collection of unique ints which is always unsorted, something like

[1, 56, 78, 89, 887, 98, 100, 0, 23, 114, 900]

I would like to quickly remove an element from the container, say 887 and the result should be

[1, 56, 78, 89, 98, 100, 0, 23, 114, 900]

I am currently using a vector and using this code to erase the element.

container.erase(std::remove(container.begin(), container.end(), elem), container.end());

where elem holds the value to be removed. This works but I have do this operation a million times or more and hence I would like to see if I can use any other algorithm or container to remove elements faster.

Morpheus
  • 3,285
  • 4
  • 27
  • 57
  • 2
    [`std::unordered_set`](https://en.cppreference.com/w/cpp/container/unordered_set) may be what you need. – JFMR Jan 29 '19 at 12:58
  • 1
    Agree with @ネロク but note that this container enforces all elements are unique (i.e. no duplicates). You didn't mention anything about that in your question, so not sure if that's a requirement. – Cory Kramer Jan 29 '19 at 12:59
  • Yes! The elements will be unique. – Morpheus Jan 29 '19 at 12:59
  • 1
    @ネロク Good chances are OP wants his *specific* unsorted order to be preserved by the container. – Sergey Kalinichenko Jan 29 '19 at 12:59
  • `std::vector`. It's always `std::vector`. – YSC Jan 29 '19 at 13:17
  • *but I have do this operation a million times* -- You didn't mention the size of the data set you're dealing with. If the number of items is small, then stay with `std::vector`. – PaulMcKenzie Jan 29 '19 at 13:20
  • @PaulMcKenzie can be between 100 to 100000 elements. I will be doing this on different sized vectors – Morpheus Jan 29 '19 at 13:21
  • 2
    @Morpheus Then I think the question is getting close to an [XY problem](http://xyproblem.info/). What is the high-level issue that you're trying to solve? Maybe using a `std::vector` to do whatever you're trying to do is not the best way, and knowing what you're trying to achieve would yield better responses. – PaulMcKenzie Jan 29 '19 at 13:24
  • 1
    I second PaulMcKenzie, and think the question would be more clear if you better explain your use case (maybe even turns out to be not a duplicate). You are not erasing a million times elements from a vector that contains 10 elements :P – 463035818_is_not_an_ai Jan 29 '19 at 13:27
  • @PaulMcKenzie I have a vector of vectors. There could be a million vectors, each of size anywhere from 10 elements to 10,000 elements in each vector. So I remove elements from these vectors one by one. – Morpheus Jan 29 '19 at 13:29
  • @Morpheus We know all this information already. What is being asked is what is the real high level problem you're trying to solve? – PaulMcKenzie Jan 29 '19 at 16:49

0 Answers0