STL迭代器失效情況總結

2021-08-08 08:36:04 字數 1839 閱讀 5175

#define _crt_secure_no_warnings

#include

#include

#include

#include

#include

#include

using

namespace

std;

void stl_vector_test()

cout

<< *it;

}cout

<< endl;

cout

<< "插在迭代器指向的元素前面,返回指向這個元素的迭代器,原迭代器失效"

<< endl;

for (it = v.begin(); it != v.end(); ++it)

}for (it = v.begin(); it != v.end(); ++it)

cout

<< endl;

cout

<< "capacity變化之後,所有的迭代器都失效"

<< endl;

it = v.begin();

#if 0

for (int i = 0; i < 9999; ++i) //錯誤

#endif

while (it != v.end())

cout

<< endl;

cout

<< "容器物件交換元素後,迭代器也交換"

<< endl;

vector

other_v;

other_v.push_back(99);

other_v.push_back(88);

it = v.begin();

v.swap(other_v);

#if 0

for (; it != v.end(); ++it) //錯誤

#else

for (; it != other_v.end(); ++it)

#endif

cout

<< endl;

}void stl_list_test()

cout

<< *it;

}cout

<< endl;

cout

<< "插在迭代器指向的元素前面,返回指向這個元素的迭代器,原迭代器失效"

<< endl;

for (it = l.begin(); it != l.end(); ++it)

}for (it = l.begin(); it != l.end(); ++it)

cout

<< endl;

cout

<< "刪除所有4的元素,他們的迭代器失效"

<< endl;

#if 0

l.remove(4);

#endif

cout

<< "容器物件交換元素後,迭代器也交換"

<< endl;

list

other_l;

other_l.push_back(99);

other_l.push_back(88);

it = l.begin();

l.swap(other_l);

#if 0

for (; it != v.end(); ++it) //錯誤

#else

for (; it != other_l.end(); ++it)

#endif

cout

<< endl;

}void stl_map_test()

}int main()

STL迭代器失效情況

vector與string有以下兩種情況會使得迭代器失效 1.若新增元素時,儲存空間足夠,沒有重新分配,則end返回的迭代器失效 若儲存空間不足,重新分配空間,則全部迭代器失效。2.刪除元素時,刪除點之前的迭代器有效,之後的迭代器失效。原因 vector與string是順序儲存 占用的是一塊連續記憶...

常見幾種stl迭代器失效情況總結

思前想後還是先多鞏固基礎在去學習新的技術為好,近期會整理一些對基礎知識的總結 迭代器失效是因為向容器插入或者刪除元素導致容器的空間變化或者說是次序發生了變化,使得原迭代器變得不可用。因此在對stl迭代器進行增刪操作時,要格外注意迭代器是否失效。下面介紹幾種常用的迭代器失效情況 list map se...

C 迭代器失效情況總結

迭代器失效分三種情況考慮,也是分三種資料結構考慮,分別為陣列型,鏈表型,樹型資料結構。陣列型資料結構 該資料結構的元素是分配在連續的記憶體中,insert和erase操作,都會使得刪除點和插入點之後的元素挪位置,所以,插入點和刪除掉之後的迭代器全部失效,也就是說insert iter 或erase ...