我想了解如何編寫一個採用const InputIterator的(獨立)函數,並在遍歷容器中的每個元素時執行一些簡單的操作。爲了簡單起見,我正在考慮一個簡單的打印功能,它將打印範圍在[first..last)
之間的所有元素,但不允許該功能修改容器中的元素。下面是我到目前爲止有:如何使用const InputIterators爲泛型容器編寫函數?
#include<iostream>
#include<vector>
#include<list>
using namespace std;
template<class InputIterator>
void print(const InputIterator& first, const InputIterator& last)
{
while (first != last) {
cout << *first << " ";
++first;
}
cout << endl;
}
int main()
{
vector<int> v;
v.push_back(1);
v.push_back(3);
v.push_back(5);
v.push_back(7);
list<float> l;
l.push_back(11.1);
l.push_back(33.3);
l.push_back(55.7);
l.push_back(77.7);
print(v.cbegin(), v.cend());
print(l.cbegin(), l.cend());
}
當我嘗試編譯代碼(使用C++ 11標誌gcc4.7),我收到以下錯誤:
iterator.cpp: In instantiation of 'void print(const InputIterator&, const InputIterator&) [with InputIterator = __gnu_cxx::__normal_iterator<const int*, std::vector<int> >]':
iterator.cpp:32:29: required from here
iterator.cpp:12:5: error: passing 'const __gnu_cxx::__normal_iterator<const int*, std::vector<int> >' as 'this' argument of '__gnu_cxx::__normal_iterator<_Iterator, _Container>& __gnu_cxx::__normal_iterator<_Iterator, _Container>::operator++() [with _Iterator = const int*; _Container = std::vector<int>; __gnu_cxx::__normal_iterator<_Iterator, _Container> = __gnu_cxx::__normal_iterator<const int*, std::vector<int> >]' discards qualifiers [-fpermissive]
iterator.cpp: In instantiation of 'void print(const InputIterator&, const InputIterator&) [with InputIterator = std::_List_const_iterator<float>]':
iterator.cpp:33:29: required from here
iterator.cpp:12:5: error: passing 'const std::_List_const_iterator<float>' as 'this' argument of 'std::_List_const_iterator<_Tp>::_Self& std::_List_const_iterator<_Tp>::operator++() [with _Tp = float; std::_List_const_iterator<_Tp>::_Self = std::_List_const_iterator<float>]' discards qualifiers [-fpermissive]
我我注意到,如果我刪除const
要求,則代碼工作正常,分別將cbegin
和cend
分別替換爲begin
和end
。有人能指出我在這裏錯過了什麼嗎?
第一個被聲明爲const,但是你試圖修改它:'++ first;' – Borgleader
你想要的是一個'const_iterator'而不是'const iterator' – NathanOliver
按值傳遞迭代器。 – 0x499602D2