插入迭代器inserter在copy函式的執行機制是什麼?

時間 2021-06-01 12:03:48

1樓:aliblielite

以下引用自sherlly666的部落格:

除了普通迭代器,C++標準模板庫還定義了幾種特殊的迭代器,分別是插入迭代器、流迭代器、反向迭代器和移動迭代器,定義在標頭檔案中,下面主要介紹三種插入迭代器(back_inserter,inserter,front_inserter)的區別。

首先,什麼是插入迭代器?插入迭代器是指被繫結在乙個容器上,可用來向容器插入元素的迭代器。

back_inserter:建立乙個使用push_back的迭代器。

inserter:此函式接受第二個引數,這個引數必須是乙個指向給定容器的迭代器。元素將被插入到給定迭代器所表示的元素之前。

front_inserter:建立乙個使用push_front的迭代器(元素總是插入到容器第乙個元素之前)。

list lst = ;

list lst2 =, lst3=,lst4=;

copy(lst.cbegin(), lst.cend(), back_inserter(lst2));

//lst2包含10,1,2,3,4,5,6,7,8,9

copy(lst.cbegin(), lst.cend(), inserter(lst3, lst3.begin()));

//lst3包含1,2,3,4,5,6,7,8,9,10

copy(lst.cbegin(), lst.cend(), front_inserter(lst4));

//lst4包含9,8,7,6,5,4,3,2,1,10

2樓:

C++ Primer 5th,p358對這個問題有較詳細解釋.

書上有句:元素將被插入到給定迭代器所表示的元素之前(這句話很會被誤解)

我的理解是inserter將元素分成容器本身(舊元素)存在的元素和新插入的元素,比如插入1後,再插入2,分為新插入的元素1和本身存在的元素(也就是空),此時copy(lst.cbegin(),lst.cend(),inserter(lst3,lst3.

begin()));這裡的lst3.begin()是指向舊元素的迭代器,所以就是1 2而不是2 1。

按輪子哥的理解就更加簡單明瞭。不知道我的理解是否有誤 @vczh ?

3樓:一根筋的傻瓜

這是copy的原始碼:

template

OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result)

return result;

}這是insert_iterator的相關原始碼:

insert_iterator& operator= (typename Container::value_type&& value)

insert_iterator& operatorreturn *this; }

insert_iterator& operatorreturn *this; }

copy(lst.cbegin(),lst.cend(),inserter(lst3,lst3.begin()));

相當於:

first = lst.cbegin();

last = lst.cend();

result = inserter(lst3,lst3.begin());

while (first!=last)

*result = *first;

這一行會使用到operator* 這個「*」過載操作符,返回的是*this。並且會使用到operator = 這個「=」的過載操作符。

這個「=」的操作符會通過list容器的iterator insert (const_iterator position, const value_type& val)成員函式插入元素的值,並將新的待插入的位置賦值給iter(也就是相當於接下來的元素可以插入的位置,是list中剛才插入的元素的下乙個位置),返回值就是An iterator that points to the first of the newly inserted elements.

所以其實就是如輪子哥所說,一直在「push_back」。

4樓:Skiiii

inserter(lst3,lst3.begin())用lst3.begin()初始化了inserter,然後新增了之後。

inserter還是那個inserter

begin已不是那個begin

C 迭代器實質是什麼

d41d8c 按照Herb Sutter的最新說法 https 是Pointer。A Pointer is not an Owner and provides indirect access to an object it does not own can dangle The following ...

請問這個 Python 迭代器裡 next 定義怎麼理解?

LiDH 首先理解迭代器。先看看C 怎麼實現乙個迭代器。在C 中,任何乙個資料型別 不論是內建型別還是類 的變數p都可以作為乙個迭代器,若同時滿足四個性質 IDEA 1 Increment p可以實現自增,並且 遍歷整個容器,即p 和 p是有意義的並可以實現遍歷 2 Dereference p可以解...

python的迭代器為什麼一定要實現 iter 方法?

劉昕宸 劉昕宸 徹底搞懂Python的 iter 和 next Iterable和Iteration iter 與 next iter 返回乙個迭代器物件,該物件是乙個實現了 next 的物件。該方法為容器類所擁有,類似於迭代器模式中Aggregate類的createIterator方法。next ...