簡體   English   中英

使用元素指針刪除列表元素

[英]Delete list element using element pointer

我想創建一個需要兩個 arguments 的方法:字符串列表和指向列表元素的指針。 接下來,我想刪除指針指向的列表項。

首先我創建一個簡單的列表:

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

我想我首先應該檢查元素是否存在:

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

如果元素存在,獲取他的指針並調用 function 刪除:

void delete(node_t *list_ptr, node_t *p)

我的問題是我不知道是否甚至可以使用其指針刪除列表項。 此外,如何獲取單個列表項的指示符?

是的,我是 C++ 新手:)

std::list有自己的刪除、排序等接口:

#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());
}

如果您想使用示例中的迭代器,請按照以下步驟操作:

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);

關於這一點,如果保留順序不是您關心的問題,您可以從std::vector的任何位置進行有效的 O(1) 刪除,這通常是一個更好的容器:

#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());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM