我想问一下back_iterator 返回什么?? 好像这两个使用back_inserter的操作矛盾了,如果它返回迭代器那么back_inserter(ivec)=10;就不对了,如果不返回迭代器,那么replace_copy第三个参数又要求是迭代器,这不是矛盾了吗?? 不知道back_inserter到底是干什么的,以及在这个例子中replace_copy到底是怎么实现的,很不解!! C++primer中只说了怎么用,咱也不知道这里的原理。求解答。 [解决办法] Copies the values of the elements in the range [first,last) to the range positions beginning at result, replacing the appearances of old_value by new_value.
實現原理大致是這樣:
template < class InputIterator, class OutputIterator, class T > OutputIterator replace_copy ( InputIterator first, InputIterator last, OutputIterator result, const T& old_value, const T& new_value ) { for (; first != last; ++first, ++result) *result = (*first==old_value)? new_value: *first; return result; }
// replace_copy example #include <iostream> #include <algorithm> #include <vector> using namespace std;
int main () { int myints[] = { 10, 20, 30, 30, 20, 10, 10, 20 };