Adam Wróbel
Adam Wróbel

Reputation: 453

Delete list element using element pointer

I'd like to create a method that takes two arguments: List of string and pointer to list element. Next, I would like to delete the list item pointed to by the pointer.

Firstly i create simple list:

list<string> list_ptr = { "1", "2", "3", "4", "5", "6", "7", "8"};

I suppose that i first should check element exist:

auto it = find(list_ptr.begin(), list_ptr.end(), "4");

And if element exist, get his pointer and call function delete:

void delete(node_t *list_ptr, node_t *p)

My problem is that I have no idea if it is even possible to delete a list item using its pointer. Additionally, how can I get the indicator of a single list item?

Yes, I am C++ newbie :)

Upvotes: 1

Views: 380

Answers (1)

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29985

std::list has its own interface for deleting, sorting, etc:

#include <stdio.h>

#include <list>
#include <string>

int main() {
  std::list<std::string> strlist = {"1", "2", "3", "4", "5", "6", "7", "8"};
  strlist.remove("4");

  for (auto const& elm : strlist) puts(elm.c_str());
}

If you want to use the iterators like in your example, here's how you do it:

std::list<std::string> strlist = {"1", "2", "3", "4", "5", "6", "7", "8"};
auto it = std::find(strlist.begin(), strlist.end(), "4");

if (it != strlist.end()) strlist.erase(it);

On that note, if preserving the ordering is not a concern for you, you can have efficient O(1) removal from anywhere in std::vector, which is generally a better containier:

#include <stdio.h>

#include <algorithm>
#include <iterator>
#include <string>
#include <vector>

int main() {
  std::vector<std::string> strvec = {"1", "2", "3", "4", "5", "6", "7", "8"};
  auto it = std::find(strvec.begin(), strvec.end(), "4");
  if (it != strvec.end()) {
    std::iter_swap(it, std::prev(strvec.end()));
    strvec.pop_back();
  }

  for (auto const& elm : strvec) puts(elm.c_str());
}

Upvotes: 1

Related Questions