Очистка std::list с удалением объектов
Суть в том, что я циклически создаю объекты и помещаю их в list. Но как мне потом средствами самого list удалить все объекты из памяти? Или прийдётся ето делать вручную?
Вывод программы такой:
MyClass::MyClass(1) MyClass::MyClass(2) MyClass::MyClass(3) MyClass::MyClass(4)
деструкторы класса не срабатывают. Может, я не правильно понимаю документацию, но здесь http://www.cplusplus.com/reference/list/list/clear/ написано:
All the elements in the list container are dropped: their destructors are called, and then they are removed from the list container, leaving it with a size of 0.
почему тогда в моём случае деструкторы не вызываются?
List.Remove(T) Метод
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Удаляет первое вхождение указанного объекта из коллекции List .
public: virtual bool Remove(T item);
public bool Remove (T item);
abstract member Remove : 'T -> bool override this.Remove : 'T -> bool
Public Function Remove (item As T) As Boolean
Параметры
Возвращаемое значение
Значение true , если элемент item успешно удален, в противном случае — значение false . Этот метод также возвращает false , если элемент item не найден в коллекции List .
Реализации
Примеры
В следующем примере показано, как добавить, удалить и вставить простой бизнес-объект в List .
using System; using System.Collections.Generic; // Simple business object. A PartId is used to identify the type of part // but the part name can change. public class Part : IEquatable < public string PartName < get; set; >public int PartId < get; set; >public override string ToString() < return "ID: " + PartId + " Name: " + PartName; >public override bool Equals(object obj) < if (obj == null) return false; Part objAsPart = obj as Part; if (objAsPart == null) return false; else return Equals(objAsPart); >public override int GetHashCode() < return PartId; >public bool Equals(Part other) < if (other == null) return false; return (this.PartId.Equals(other.PartId)); >// Should also override == and != operators. > public class Example < public static void Main() < // Create a list of parts. Listparts = new List(); // Add parts to the list. parts.Add(new Part() < PartName = "crank arm", PartId = 1234 >); parts.Add(new Part() < PartName = "chain ring", PartId = 1334 >); parts.Add(new Part() < PartName = "regular seat", PartId = 1434 >); parts.Add(new Part() < PartName = "banana seat", PartId = 1444 >); parts.Add(new Part() < PartName = "cassette", PartId = 1534 >); parts.Add(new Part() < PartName = "shift lever", PartId = 1634 >); // Write out the parts in the list. This will call the overridden ToString method // in the Part class. Console.WriteLine(); foreach (Part aPart in parts) < Console.WriteLine(aPart); >// Check the list for part #1734. This calls the IEquatable.Equals method // of the Part class, which checks the PartId for equality. Console.WriteLine("\nContains(\"1734\"): ", parts.Contains(new Part < PartId = 1734, PartName = "" >)); // Insert a new item at position 2. Console.WriteLine("\nInsert(2, \"1834\")"); parts.Insert(2, new Part() < PartName = "brake lever", PartId = 1834 >); //Console.WriteLine(); foreach (Part aPart in parts) < Console.WriteLine(aPart); >Console.WriteLine("\nParts[3]: ", parts[3]); Console.WriteLine("\nRemove(\"1534\")"); // This will remove part 1534 even though the PartName is different, // because the Equals method only checks PartId for equality. parts.Remove(new Part() < PartId = 1534, PartName = "cogs" >); Console.WriteLine(); foreach (Part aPart in parts) < Console.WriteLine(aPart); >Console.WriteLine("\nRemoveAt(3)"); // This will remove the part at index 3. parts.RemoveAt(3); Console.WriteLine(); foreach (Part aPart in parts) < Console.WriteLine(aPart); >/* ID: 1234 Name: crank arm ID: 1334 Name: chain ring ID: 1434 Name: regular seat ID: 1444 Name: banana seat ID: 1534 Name: cassette ID: 1634 Name: shift lever Contains("1734"): False Insert(2, "1834") ID: 1234 Name: crank arm ID: 1334 Name: chain ring ID: 1834 Name: brake lever ID: 1434 Name: regular seat ID: 1444 Name: banana seat ID: 1534 Name: cassette ID: 1634 Name: shift lever Parts[3]: ID: 1434 Name: regular seat Remove("1534") ID: 1234 Name: crank arm ID: 1334 Name: chain ring ID: 1834 Name: brake lever ID: 1434 Name: regular seat ID: 1444 Name: banana seat ID: 1634 Name: shift lever RemoveAt(3) ID: 1234 Name: crank arm ID: 1334 Name: chain ring ID: 1834 Name: brake lever ID: 1444 Name: banana seat ID: 1634 Name: shift lever */ > >
Imports System.Collections.Generic ' Simple business object. A PartId is used to identify the type of part ' but the part name can change. Public Class Part Implements IEquatable(Of Part) Public Property PartName() As String Get Return m_PartName End Get Set(value As String) m_PartName = Value End Set End Property Private m_PartName As String Public Property PartId() As Integer Get Return m_PartId End Get Set(value As Integer) m_PartId = Value End Set End Property Private m_PartId As Integer Public Overrides Function ToString() As String Return "ID: " & PartId & " Name: " & PartName End Function Public Overrides Function Equals(obj As Object) As Boolean If obj Is Nothing Then Return False End If Dim objAsPart As Part = TryCast(obj, Part) If objAsPart Is Nothing Then Return False Else Return Equals(objAsPart) End If End Function Public Overrides Function GetHashCode() As Integer Return PartId End Function Public Overloads Function Equals(other As Part) As Boolean _ Implements IEquatable(Of Part).Equals If other Is Nothing Then Return False End If Return (Me.PartId.Equals(other.PartId)) End Function ' Should also override == and != operators. End Class Public Class Example Public Shared Sub Main() ' Create a list of parts. Dim parts As New List(Of Part)() ' Add parts to the list. parts.Add(New Part() With < _ .PartName = "crank arm", _ .PartId = 1234 _ >) parts.Add(New Part() With < _ .PartName = "chain ring", _ .PartId = 1334 _ >) parts.Add(New Part() With < _ .PartName = "regular seat", _ .PartId = 1434 _ >) parts.Add(New Part() With < _ .PartName = "banana seat", _ .PartId = 1444 _ >) parts.Add(New Part() With < _ .PartName = "cassette", _ .PartId = 1534 _ >) parts.Add(New Part() With < _ .PartName = "shift lever", _ .PartId = 1634 _ >) ' Write out the parts in the list. This will call the overridden ToString method ' in the Part class. Console.WriteLine() For Each aPart As Part In parts Console.WriteLine(aPart) Next ' Check the list for part #1734. This calls the IEquatable.Equals method ' of the Part class, which checks the PartId for equality. Console.WriteLine(vbLf & "Contains(""1734""): ", parts.Contains(New Part() With < _ .PartId = 1734, _ .PartName = "" _ >)) ' Insert a new item at position 2. Console.WriteLine(vbLf & "Insert(2, ""1834"")") parts.Insert(2, New Part() With < _ .PartName = "brake lever", _ .PartId = 1834 _ >) 'Console.WriteLine(); For Each aPart As Part In parts Console.WriteLine(aPart) Next Console.WriteLine(vbLf & "Parts[3]: ", parts(3)) Console.WriteLine(vbLf & "Remove(""1534"")") ' This will remove part 1534 even though the PartName is different, ' because the Equals method only checks PartId for equality. parts.Remove(New Part() With < _ .PartId = 1534, _ .PartName = "cogs" _ >) Console.WriteLine() For Each aPart As Part In parts Console.WriteLine(aPart) Next Console.WriteLine(vbLf & "RemoveAt(3)") ' This will remove part at index 3. parts.RemoveAt(3) Console.WriteLine() For Each aPart As Part In parts Console.WriteLine(aPart) Next End Sub ' ' This example code produces the following output: ' ID: 1234 Name: crank arm ' ID: 1334 Name: chain ring ' ID: 1434 Name: regular seat ' ID: 1444 Name: banana seat ' ID: 1534 Name: cassette ' ID: 1634 Name: shift lever ' ' Contains("1734"): False ' ' Insert(2, "1834") ' ID: 1234 Name: crank arm ' ID: 1334 Name: chain ring ' ID: 1834 Name: brake lever ' ID: 1434 Name: regular seat ' ID: 1444 Name: banana seat ' ID: 1534 Name: cassette ' ID: 1634 Name: shift lever ' ' Parts[3]: ID: 1434 Name: regular seat ' ' Remove("1534") ' ' ID: 1234 Name: crank arm ' ID: 1334 Name: chain ring ' ID: 1834 Name: brake lever ' ID: 1434 Name: regular seat ' ID: 1444 Name: banana seat ' ID: 1634 Name: shift lever ' ' ' RemoveAt(3) ' ' ID: 1234 Name: crank arm ' ID: 1334 Name: chain ring ' ID: 1834 Name: brake lever ' ID: 1444 Name: banana seat ' ID: 1634 Name: shift lever ' End Class
// Simple business object. A PartId is used to identify the type of part // but the part name can change. [] type Part = < PartId : int ; mutable PartName : string >with override this.GetHashCode() = hash this.PartId override this.Equals(other) = match other with | :? Part as p -> this.PartId = p.PartId | _ -> false override this.ToString() = sprintf "ID: %i Name: %s" this.PartId this.PartName [] let main argv = // We refer to System.Collections.Generic.List by its type // abbreviation ResizeArray to avoid conflicts with the F# List module. // Note: In F# code, F# linked lists are usually preferred over // ResizeArray when an extendable collection is required. let parts = ResizeArray() parts.Add() parts.Add() parts.Add() parts.Add() parts.Add() parts.Add() // Write out the parts in the ResizeArray. This will call the overridden ToString method // in the Part type printfn "" parts |> Seq.iter (fun p -> printfn "%O" p) // Check the ResizeArray for part #1734. This calls the IEquatable.Equals method // of the Part type, which checks the PartId for equality. printfn "\nContains(\"1734\"): %b" (parts.Contains()) // Insert a new item at position 2. printfn "\nInsert(2, \"1834\")" parts.Insert(2, < PartName = "brake lever"; PartId = 1834 >) // Write out all parts parts |> Seq.iter (fun p -> printfn "%O" p) printfn "\nParts[3]: %O" parts.[3] printfn "\nRemove(\"1534\")" // This will remove part 1534 even though the PartName is different, // because the Equals method only checks PartId for equality. // Since Remove returns true or false, we need to ignore the result parts.Remove() |> ignore // Write out all parts printfn "" parts |> Seq.iter (fun p -> printfn "%O" p) printfn "\nRemoveAt(3)" // This will remove the part at index 3. parts.RemoveAt(3) // Write out all parts printfn "" parts |> Seq.iter (fun p -> printfn "%O" p) 0 // return an integer exit code
В следующем примере показан Remove метод . Для добавления, вставки и поиска списка используются несколько свойств и методов List универсального класса. После этих операций список содержит дубликат. Метод Remove используется для удаления первого экземпляра повторяющегося элемента, и содержимое отображается. Метод Remove всегда удаляет первый экземпляр, который он встречает.
using namespace System; using namespace System::Collections::Generic; void main() < List^ dinosaurs = gcnew List(); Console::WriteLine("\nCapacity: ", dinosaurs->Capacity); dinosaurs->Add("Tyrannosaurus"); dinosaurs->Add("Amargasaurus"); dinosaurs->Add("Mamenchisaurus"); dinosaurs->Add("Deinonychus"); dinosaurs->Add("Compsognathus"); Console::WriteLine(); for each(String^ dinosaur in dinosaurs ) < Console::WriteLine(dinosaur); >Console::WriteLine("\nCapacity: ", dinosaurs->Capacity); Console::WriteLine("Count: ", dinosaurs->Count); Console::WriteLine("\nContains(\"Deinonychus\"): ", dinosaurs->Contains("Deinonychus")); Console::WriteLine("\nInsert(2, \"Compsognathus\")"); dinosaurs->Insert(2, "Compsognathus"); Console::WriteLine(); for each(String^ dinosaur in dinosaurs ) < Console::WriteLine(dinosaur); >Console::WriteLine("\ndinosaurs[3]: ", dinosaurs[3]); Console::WriteLine("\nRemove(\"Compsognathus\")"); dinosaurs->Remove("Compsognathus"); Console::WriteLine(); for each(String^ dinosaur in dinosaurs ) < Console::WriteLine(dinosaur); >dinosaurs->TrimExcess(); Console::WriteLine("\nTrimExcess()"); Console::WriteLine("Capacity: ", dinosaurs->Capacity); Console::WriteLine("Count: ", dinosaurs->Count); dinosaurs->Clear(); Console::WriteLine("\nClear()"); Console::WriteLine("Capacity: ", dinosaurs->Capacity); Console::WriteLine("Count: ", dinosaurs->Count); > /* This code example produces the following output: Capacity: 0 Tyrannosaurus Amargasaurus Mamenchisaurus Deinonychus Compsognathus Capacity: 8 Count: 5 Contains("Deinonychus"): True Insert(2, "Compsognathus") Tyrannosaurus Amargasaurus Compsognathus Mamenchisaurus Deinonychus Compsognathus dinosaurs[3]: Mamenchisaurus Remove("Compsognathus") Tyrannosaurus Amargasaurus Mamenchisaurus Deinonychus Compsognathus TrimExcess() Capacity: 5 Count: 5 Clear() Capacity: 5 Count: 0 */
List dinosaurs = new List(); Console.WriteLine("\nCapacity: ", dinosaurs.Capacity); dinosaurs.Add("Tyrannosaurus"); dinosaurs.Add("Amargasaurus"); dinosaurs.Add("Mamenchisaurus"); dinosaurs.Add("Deinonychus"); dinosaurs.Add("Compsognathus"); Console.WriteLine(); foreach(string dinosaur in dinosaurs) < Console.WriteLine(dinosaur); >Console.WriteLine("\nCapacity: ", dinosaurs.Capacity); Console.WriteLine("Count: ", dinosaurs.Count); Console.WriteLine("\nContains(\"Deinonychus\"): ", dinosaurs.Contains("Deinonychus")); Console.WriteLine("\nInsert(2, \"Compsognathus\")"); dinosaurs.Insert(2, "Compsognathus"); Console.WriteLine(); foreach(string dinosaur in dinosaurs) < Console.WriteLine(dinosaur); >// Shows accessing the list using the Item property. Console.WriteLine("\ndinosaurs[3]: ", dinosaurs[3]); Console.WriteLine("\nRemove(\"Compsognathus\")"); dinosaurs.Remove("Compsognathus"); Console.WriteLine(); foreach(string dinosaur in dinosaurs) < Console.WriteLine(dinosaur); >dinosaurs.TrimExcess(); Console.WriteLine("\nTrimExcess()"); Console.WriteLine("Capacity: ", dinosaurs.Capacity); Console.WriteLine("Count: ", dinosaurs.Count); dinosaurs.Clear(); Console.WriteLine("\nClear()"); Console.WriteLine("Capacity: ", dinosaurs.Capacity); Console.WriteLine("Count: ", dinosaurs.Count); /* This code example produces the following output: Capacity: 0 Tyrannosaurus Amargasaurus Mamenchisaurus Deinonychus Compsognathus Capacity: 8 Count: 5 Contains("Deinonychus"): True Insert(2, "Compsognathus") Tyrannosaurus Amargasaurus Compsognathus Mamenchisaurus Deinonychus Compsognathus dinosaurs[3]: Mamenchisaurus Remove("Compsognathus") Tyrannosaurus Amargasaurus Mamenchisaurus Deinonychus Compsognathus TrimExcess() Capacity: 5 Count: 5 Clear() Capacity: 5 Count: 0 */
Imports System.Collections.Generic Public Class Example Public Shared Sub Main() Dim dinosaurs As New List(Of String) Console.WriteLine(vbLf & "Capacity: ", dinosaurs.Capacity) dinosaurs.Add("Tyrannosaurus") dinosaurs.Add("Amargasaurus") dinosaurs.Add("Mamenchisaurus") dinosaurs.Add("Deinonychus") dinosaurs.Add("Compsognathus") Console.WriteLine() For Each dinosaur As String In dinosaurs Console.WriteLine(dinosaur) Next Console.WriteLine(vbLf & "Capacity: ", dinosaurs.Capacity) Console.WriteLine("Count: ", dinosaurs.Count) Console.WriteLine(vbLf & "Contains(""Deinonychus""): ", _ dinosaurs.Contains("Deinonychus")) Console.WriteLine(vbLf & "Insert(2, ""Compsognathus"")") dinosaurs.Insert(2, "Compsognathus") Console.WriteLine() For Each dinosaur As String In dinosaurs Console.WriteLine(dinosaur) Next ' Shows how to access the list using the Item property. Console.WriteLine(vbLf & "dinosaurs(3): ", dinosaurs(3)) Console.WriteLine(vbLf & "Remove(""Compsognathus"")") dinosaurs.Remove("Compsognathus") Console.WriteLine() For Each dinosaur As String In dinosaurs Console.WriteLine(dinosaur) Next dinosaurs.TrimExcess() Console.WriteLine(vbLf & "TrimExcess()") Console.WriteLine("Capacity: ", dinosaurs.Capacity) Console.WriteLine("Count: ", dinosaurs.Count) dinosaurs.Clear() Console.WriteLine(vbLf & "Clear()") Console.WriteLine("Capacity: ", dinosaurs.Capacity) Console.WriteLine("Count: ", dinosaurs.Count) End Sub End Class ' This code example produces the following output: ' 'Capacity: 0 ' 'Tyrannosaurus 'Amargasaurus 'Mamenchisaurus 'Deinonychus 'Compsognathus ' 'Capacity: 8 'Count: 5 ' 'Contains("Deinonychus"): True ' 'Insert(2, "Compsognathus") ' 'Tyrannosaurus 'Amargasaurus 'Compsognathus 'Mamenchisaurus 'Deinonychus 'Compsognathus ' 'dinosaurs(3): Mamenchisaurus ' 'Remove("Compsognathus") ' 'Tyrannosaurus 'Amargasaurus 'Mamenchisaurus 'Deinonychus 'Compsognathus ' 'TrimExcess() 'Capacity: 5 'Count: 5 ' 'Clear() 'Capacity: 5 'Count: 0
[] let main argv = // We refer to System.Collections.Generic.List by its type // abbreviation ResizeArray to avoid conflict with the List module. // Note: In F# code, F# linked lists are usually preferred over // ResizeArray when an extendable collection is required. let dinosaurs = ResizeArray() // Write out the dinosaurs in the ResizeArray. let printDinosaurs() = printfn "" dinosaurs |> Seq.iter (fun p -> printfn "%O" p) printfn "\nCapacity: %i" dinosaurs.Capacity dinosaurs.Add("Tyrannosaurus") dinosaurs.Add("Amargasaurus") dinosaurs.Add("Mamenchisaurus") dinosaurs.Add("Deinonychus") dinosaurs.Add("Compsognathus") printDinosaurs() printfn "\nCapacity: %i" dinosaurs.Capacity printfn "Count: %i" dinosaurs.Count printfn "\nContains(\"Deinonychus\"): %b" (dinosaurs.Contains("Deinonychus")) printfn "\nInsert(2, \"Compsognathus\")" dinosaurs.Insert(2, "Compsognathus") printDinosaurs() // Shows accessing the list using the Item property. printfn "\ndinosaurs[3]: %s" dinosaurs.[3] printfn "\nRemove(\"Compsognathus\")" dinosaurs.Remove("Compsognathus") |> ignore printDinosaurs() dinosaurs.TrimExcess() printfn "\nTrimExcess()" printfn "Capacity: %i" dinosaurs.Capacity printfn "Count: %i" dinosaurs.Count dinosaurs.Clear() printfn "\nClear()" printfn "Capacity: %i" dinosaurs.Capacity printfn "Count: %i" dinosaurs.Count 0 // return an integer exit code (* This code example produces the following output: Capacity: 0 Tyrannosaurus Amargasaurus Mamenchisaurus Deinonychus Compsognathus Capacity: 8 Count: 5 Contains("Deinonychus"): true Insert(2, "Compsognathus") Tyrannosaurus Amargasaurus Compsognathus Mamenchisaurus Deinonychus Compsognathus dinosaurs[3]: Mamenchisaurus Remove("Compsognathus") Tyrannosaurus Amargasaurus Mamenchisaurus Deinonychus Compsognathus TrimExcess() Capacity: 5 Count: 5 Clear() Capacity: 5 Count: 0 *)
Комментарии
Если тип T реализует универсальный IEquatable интерфейс, компаратор на равенство является Equals методом этого интерфейса; в противном случае компаратор на равенство по умолчанию — Object.Equals.
Этот метод выполняет линейный поиск; таким образом, этот метод является операцией O(n), где n — .Count
Как очистить list c
Приветствую,
возникла проблема с удаление елемента списка.
list int> c1; list int>::iterator c1_Iter; for ( c1_Iter = c1.begin( ); c1_Iter != c1.end( ); c1_Iter++ ) < //что-то делаем с c1_Iter и поняли что нужно удалить этот элемент, но чтобы цикл продолжился >
c1.erase(c1_Iter); всё рушит и я почти понял почему
Подскажите как правильно удалить, пока приходит на ум только создать второй список на удаление и после цикла for все удалить.
Re: erase в std:list
| От: | Bell | |
| Дата: | 03.05.06 15:16 | |
| Оценка: | 1 (1) | |
Здравствуйте, RSNT, Вы писали:
RSN>Приветствую,
RSN>возникла проблема с удаление елемента списка.
RSN> list int> c1; RSN> list int>::iterator c1_Iter; RSN>for ( c1_Iter = c1.begin( ); c1_Iter != c1.end( ); c1_Iter++ ) RSN>< RSN>//что-то делаем с c1_Iter и поняли что нужно удалить этот элемент, но чтобы цикл продолжился RSN>> RSN>
RSN>c1.erase(c1_Iter); всё рушит и я почти понял почему
RSN>Подскажите как правильно удалить, пока приходит на ум только создать второй список на удаление и после цикла for все удалить.
list int> c1; list int>::iterator c1_Iter = c1.begin(), e = c1.end(); while(c1_Iter != e) < if(/*нужно удалить*/) c1_Iter = c1.erase(c1_Iter); else ++c1_Iter; >
Или же использовать метод списка remove_if.
Любите книгу — источник знаний (с) М.Горький
Re[2]: erase в std:list
| От: | denisku |
| Дата: | 04.05.06 10:48 |
| Оценка: |
Здравствуйте, Bell, Вы писали:
B>
B>list int> c1; B> list int>::iterator c1_Iter = c1.begin(), e = c1.end(); B>while(c1_Iter != e) B> < B>if(/*нужно удалить*/) B> c1_Iter = c1.erase(c1_Iter); B> else B> ++c1_Iter; B>> B>
а вызов erase() не сделает e невалидным? имхо, надо бы сделать
while(c1_Iter != c1.end())
Извините за потраченный траффик..
Re[3]: erase в std:list
| От: | FreshMeat | http://www.rsdn.org |
| Дата: | 04.05.06 10:57 | |
| Оценка: |
Здравствуйте, denisku, Вы писали:
D>а вызов erase() не сделает e невалидным?
Нет. Добавление/удаление элементов списка не влияет на валидность итераторов (видимо, с вектором спутал)
http://gzip.rsdn.ru/article/cpp/stl.xml#EMVBG
Автор(ы): Александр Степанов, Менг Ли
Список (List)
.
erase делает недействительными только итераторы и ссылки для стёртых элементов. Стирание единственного элемента — операция постоянного времени с единственным вызовом деструктора T. Стирание диапазона в списке занимает линейное время от размера диапазона, а число вызовов деструктора типа T точно равно размеру диапазона.
Хорошо там, где мы есть! 🙂
Re[4]: erase в std:list
| От: | saddva |
| Дата: | 04.05.06 12:54 |
| Оценка: |
Здравствуйте, FreshMeat, Вы писали:
FM>Здравствуйте, denisku, Вы писали:
D>>а вызов erase() не сделает e невалидным?
FM>Нет. Добавление/удаление элементов списка не влияет на валидность итераторов (видимо, с вектором спутал)
FM>http://gzip.rsdn.ru/article/cpp/stl.xml#EMVBG
Автор(ы): Александр Степанов, Менг Ли
FM>Список (List)
FM>.
FM>erase делает недействительными только итераторы и ссылки для стёртых элементов. Стирание единственного элемента — операция постоянного времени с единственным вызовом деструктора T. Стирание диапазона в списке занимает линейное время от размера диапазона, а число вызовов деструктора типа T точно равно размеру диапазона.
А если удаляется последний элемент списка? Даже в этом случае e останется валидным?
Re[5]: erase в std:list
| От: | FreshMeat | http://www.rsdn.org |
| Дата: | 04.05.06 13:06 | |
| Оценка: |
Здравствуйте, saddva, Вы писали:
S>А если удаляется последний элемент списка? Даже в этом случае e останется валидным?
Да. end() у списка сделан вообще достаточно хитро. Сырцы реализаций STL не копал, но есть сильное подозрение (следующее из логики работы класса), что end() фиксируется в момент создания списка и не изменяется все время жизни листа.
Хорошо там, где мы есть! 🙂
Re: erase в std:list
| От: | rg45 |
| Дата: | 05.05.06 14:00 |
| Оценка: |
> list int> c1; > list int>::iterator c1_Iter; > > for ( c1_Iter = c1.begin( ); c1_Iter != c1.end( ); c1_Iter++ ) > < >//что-то делаем с c1_Iter и поняли что нужно удалить этот элемент, но чтобы цикл продолжился > > > >
>
> c1.erase(c1_Iter); всё рушит и я почти понял почему
>
> Подскажите как правильно удалить, пока приходит на ум только создать второй список на удаление и после цикла for все удалить.
При помощи вспомогательного итератора проблема решается достаточно просто:
list int> c1; list int>::iterator c1_Iter, c1_Iter2; for ( c1_Iter = c1_Iter2 = c1.begin( ); c1_Iter != c1.end( ); c1_Iter = c1_Iter2) < ++c1_Iter2; //что-то делаем с c1_Iter. c1.erase(c1_Iter); >
List.Clear Метод
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
public: virtual void Clear();
public void Clear ();
abstract member Clear : unit -> unit override this.Clear : unit -> unit
Public Sub Clear ()
Реализации
Примеры
В следующем примере демонстрируется Clear метод и различные другие свойства и методы универсального List класса. Метод Clear используется в конце программы для удаления всех элементов из списка, а Capacity затем отображаются свойства и Count .
using namespace System; using namespace System::Collections::Generic; void main() < List^ dinosaurs = gcnew List(); Console::WriteLine("\nCapacity: ", dinosaurs->Capacity); dinosaurs->Add("Tyrannosaurus"); dinosaurs->Add("Amargasaurus"); dinosaurs->Add("Mamenchisaurus"); dinosaurs->Add("Deinonychus"); dinosaurs->Add("Compsognathus"); Console::WriteLine(); for each(String^ dinosaur in dinosaurs ) < Console::WriteLine(dinosaur); >Console::WriteLine("\nCapacity: ", dinosaurs->Capacity); Console::WriteLine("Count: ", dinosaurs->Count); Console::WriteLine("\nContains(\"Deinonychus\"): ", dinosaurs->Contains("Deinonychus")); Console::WriteLine("\nInsert(2, \"Compsognathus\")"); dinosaurs->Insert(2, "Compsognathus"); Console::WriteLine(); for each(String^ dinosaur in dinosaurs ) < Console::WriteLine(dinosaur); >Console::WriteLine("\ndinosaurs[3]: ", dinosaurs[3]); Console::WriteLine("\nRemove(\"Compsognathus\")"); dinosaurs->Remove("Compsognathus"); Console::WriteLine(); for each(String^ dinosaur in dinosaurs ) < Console::WriteLine(dinosaur); >dinosaurs->TrimExcess(); Console::WriteLine("\nTrimExcess()"); Console::WriteLine("Capacity: ", dinosaurs->Capacity); Console::WriteLine("Count: ", dinosaurs->Count); dinosaurs->Clear(); Console::WriteLine("\nClear()"); Console::WriteLine("Capacity: ", dinosaurs->Capacity); Console::WriteLine("Count: ", dinosaurs->Count); > /* This code example produces the following output: Capacity: 0 Tyrannosaurus Amargasaurus Mamenchisaurus Deinonychus Compsognathus Capacity: 8 Count: 5 Contains("Deinonychus"): True Insert(2, "Compsognathus") Tyrannosaurus Amargasaurus Compsognathus Mamenchisaurus Deinonychus Compsognathus dinosaurs[3]: Mamenchisaurus Remove("Compsognathus") Tyrannosaurus Amargasaurus Mamenchisaurus Deinonychus Compsognathus TrimExcess() Capacity: 5 Count: 5 Clear() Capacity: 5 Count: 0 */
List dinosaurs = new List(); Console.WriteLine("\nCapacity: ", dinosaurs.Capacity); dinosaurs.Add("Tyrannosaurus"); dinosaurs.Add("Amargasaurus"); dinosaurs.Add("Mamenchisaurus"); dinosaurs.Add("Deinonychus"); dinosaurs.Add("Compsognathus"); Console.WriteLine(); foreach(string dinosaur in dinosaurs) < Console.WriteLine(dinosaur); >Console.WriteLine("\nCapacity: ", dinosaurs.Capacity); Console.WriteLine("Count: ", dinosaurs.Count); Console.WriteLine("\nContains(\"Deinonychus\"): ", dinosaurs.Contains("Deinonychus")); Console.WriteLine("\nInsert(2, \"Compsognathus\")"); dinosaurs.Insert(2, "Compsognathus"); Console.WriteLine(); foreach(string dinosaur in dinosaurs) < Console.WriteLine(dinosaur); >// Shows accessing the list using the Item property. Console.WriteLine("\ndinosaurs[3]: ", dinosaurs[3]); Console.WriteLine("\nRemove(\"Compsognathus\")"); dinosaurs.Remove("Compsognathus"); Console.WriteLine(); foreach(string dinosaur in dinosaurs) < Console.WriteLine(dinosaur); >dinosaurs.TrimExcess(); Console.WriteLine("\nTrimExcess()"); Console.WriteLine("Capacity: ", dinosaurs.Capacity); Console.WriteLine("Count: ", dinosaurs.Count); dinosaurs.Clear(); Console.WriteLine("\nClear()"); Console.WriteLine("Capacity: ", dinosaurs.Capacity); Console.WriteLine("Count: ", dinosaurs.Count); /* This code example produces the following output: Capacity: 0 Tyrannosaurus Amargasaurus Mamenchisaurus Deinonychus Compsognathus Capacity: 8 Count: 5 Contains("Deinonychus"): True Insert(2, "Compsognathus") Tyrannosaurus Amargasaurus Compsognathus Mamenchisaurus Deinonychus Compsognathus dinosaurs[3]: Mamenchisaurus Remove("Compsognathus") Tyrannosaurus Amargasaurus Mamenchisaurus Deinonychus Compsognathus TrimExcess() Capacity: 5 Count: 5 Clear() Capacity: 5 Count: 0 */
Imports System.Collections.Generic Public Class Example Public Shared Sub Main() Dim dinosaurs As New List(Of String) Console.WriteLine(vbLf & "Capacity: ", dinosaurs.Capacity) dinosaurs.Add("Tyrannosaurus") dinosaurs.Add("Amargasaurus") dinosaurs.Add("Mamenchisaurus") dinosaurs.Add("Deinonychus") dinosaurs.Add("Compsognathus") Console.WriteLine() For Each dinosaur As String In dinosaurs Console.WriteLine(dinosaur) Next Console.WriteLine(vbLf & "Capacity: ", dinosaurs.Capacity) Console.WriteLine("Count: ", dinosaurs.Count) Console.WriteLine(vbLf & "Contains(""Deinonychus""): ", _ dinosaurs.Contains("Deinonychus")) Console.WriteLine(vbLf & "Insert(2, ""Compsognathus"")") dinosaurs.Insert(2, "Compsognathus") Console.WriteLine() For Each dinosaur As String In dinosaurs Console.WriteLine(dinosaur) Next ' Shows how to access the list using the Item property. Console.WriteLine(vbLf & "dinosaurs(3): ", dinosaurs(3)) Console.WriteLine(vbLf & "Remove(""Compsognathus"")") dinosaurs.Remove("Compsognathus") Console.WriteLine() For Each dinosaur As String In dinosaurs Console.WriteLine(dinosaur) Next dinosaurs.TrimExcess() Console.WriteLine(vbLf & "TrimExcess()") Console.WriteLine("Capacity: ", dinosaurs.Capacity) Console.WriteLine("Count: ", dinosaurs.Count) dinosaurs.Clear() Console.WriteLine(vbLf & "Clear()") Console.WriteLine("Capacity: ", dinosaurs.Capacity) Console.WriteLine("Count: ", dinosaurs.Count) End Sub End Class ' This code example produces the following output: ' 'Capacity: 0 ' 'Tyrannosaurus 'Amargasaurus 'Mamenchisaurus 'Deinonychus 'Compsognathus ' 'Capacity: 8 'Count: 5 ' 'Contains("Deinonychus"): True ' 'Insert(2, "Compsognathus") ' 'Tyrannosaurus 'Amargasaurus 'Compsognathus 'Mamenchisaurus 'Deinonychus 'Compsognathus ' 'dinosaurs(3): Mamenchisaurus ' 'Remove("Compsognathus") ' 'Tyrannosaurus 'Amargasaurus 'Mamenchisaurus 'Deinonychus 'Compsognathus ' 'TrimExcess() 'Capacity: 5 'Count: 5 ' 'Clear() 'Capacity: 5 'Count: 0
[] let main argv = // We refer to System.Collections.Generic.List by its type // abbreviation ResizeArray to avoid conflict with the List module. // Note: In F# code, F# linked lists are usually preferred over // ResizeArray when an extendable collection is required. let dinosaurs = ResizeArray() // Write out the dinosaurs in the ResizeArray. let printDinosaurs() = printfn "" dinosaurs |> Seq.iter (fun p -> printfn "%O" p) printfn "\nCapacity: %i" dinosaurs.Capacity dinosaurs.Add("Tyrannosaurus") dinosaurs.Add("Amargasaurus") dinosaurs.Add("Mamenchisaurus") dinosaurs.Add("Deinonychus") dinosaurs.Add("Compsognathus") printDinosaurs() printfn "\nCapacity: %i" dinosaurs.Capacity printfn "Count: %i" dinosaurs.Count printfn "\nContains(\"Deinonychus\"): %b" (dinosaurs.Contains("Deinonychus")) printfn "\nInsert(2, \"Compsognathus\")" dinosaurs.Insert(2, "Compsognathus") printDinosaurs() // Shows accessing the list using the Item property. printfn "\ndinosaurs[3]: %s" dinosaurs.[3] printfn "\nRemove(\"Compsognathus\")" dinosaurs.Remove("Compsognathus") |> ignore printDinosaurs() dinosaurs.TrimExcess() printfn "\nTrimExcess()" printfn "Capacity: %i" dinosaurs.Capacity printfn "Count: %i" dinosaurs.Count dinosaurs.Clear() printfn "\nClear()" printfn "Capacity: %i" dinosaurs.Capacity printfn "Count: %i" dinosaurs.Count 0 // return an integer exit code (* This code example produces the following output: Capacity: 0 Tyrannosaurus Amargasaurus Mamenchisaurus Deinonychus Compsognathus Capacity: 8 Count: 5 Contains("Deinonychus"): true Insert(2, "Compsognathus") Tyrannosaurus Amargasaurus Compsognathus Mamenchisaurus Deinonychus Compsognathus dinosaurs[3]: Mamenchisaurus Remove("Compsognathus") Tyrannosaurus Amargasaurus Mamenchisaurus Deinonychus Compsognathus TrimExcess() Capacity: 5 Count: 5 Clear() Capacity: 5 Count: 0 *)
Комментарии
Count имеет значение 0, а ссылки на другие объекты из элементов коллекции также освобождаются.
Capacity остается без изменений. Чтобы сбросить емкость List , вызовите TrimExcess метод или задайте Capacity свойство напрямую. Уменьшение емкости перераспределяет память и копирует все элементы в List . Удаление пустой List задает емкость объекта List емкость по умолчанию.
Этот метод является операцией O(n), где n — .Count