Reputation: 47
I need help in the simple matter
Im trying to create class
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
template<class T> class merge_sort
{
protected:
vector<T> merge(const vector<T> &a, const vector<T> &b)
{
vector<T> v;
typename vector<T>::iterator A;
A= a.begin();
typename vector<T>::iterator B;
B= b.begin();
...
but compiler gives me next error:
no match for ‘operator=’ in ‘A = ((const std::vector<int, std::allocator<int> >*)a)->std::vector<_Tp, _Alloc>::begin [with _Tp = int, _Alloc = std::allocator<int>]()’ merge.cpp /merge_sort line 23 C/C++ Problem
Upvotes: 1
Views: 2775
Reputation: 56956
Use
typename vector<T>::const_iterator A = a.begin();
typename vector<T>::const_iterator B = b.begin();
because a
and b
are const references, the const version of begin
is called, and it returns a const_iterator
, not an iterator
. You cannot assign const_iterator
s to iterator
s, like you cannot assign pointers-to-const to pointers.
Upvotes: 7
Reputation: 7769
You are confusing a typedef with a decaration.
If you want to declare a typedef with a dependent type, then you do need to use the typename keyword:
typedef typename vector<T>::const_iterator iter
iter A = a.begin( );
iter B = b.begin( );
BTW, typename is required even without the typedef.
Upvotes: 0
Reputation: 51711
typename vector<T>::iterator A;
Should be
typename vector<T>::const_iterator A;
Same for B
Update
My C++ skills are rusty, but
Because the two vectors
passed to merge are const references, you cannot use a standard iterator to move over them, because the standard iterator allows you to modify the contents of the vector. Therefore, you must use const_iterator
's which will not allow you to modify the vector contents.
Apologies if my C++ Fu isn't up to scratch, I remember enough C++ to fix the problem, but haven't used C++ in anger in . . . wow 7 years (is it really that long? Bugger me but I'm getting old).
As I said, feel free to edit this answer if you can provide better explanations.
Upvotes: 3