C ++模板和STL向量问题

我在简单的事情上需要帮助 我试图创建课程
#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();
...
但编译器给我下一个错误:
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
    
已邀请:
使用
typename vector<T>::const_iterator A = a.begin();
typename vector<T>::const_iterator B = b.begin();
因为
a
b
是const引用,所以调用
begin
的const版本,它返回一个
const_iterator
,而不是一个
iterator
。你不能将
const_iterator
s分配给
iterator
s,就像你不能指定指针指针一样。     
typename vector<T>::iterator A;
应该
typename vector<T>::const_iterator A;
B也一样 更新 我的C ++技能很生疏,但是 因为传递给merge的两个
vectors
是const引用,所以不能使用标准迭代器移过它们,因为标准迭代器允许你修改向量的内容。因此,您必须使用
const_iterator
,这将不允许您修改矢量内容。 抱歉,如果我的C ++ Fu没有达到标准,我记得有足够的C ++来解决这个问题,但是我没有在愤怒中使用过C ++。 。 。哇7年(真的那么长吗?告诉我,但我已经老了)。 正如我所说,如果您能提供更好的解释,请随时编辑此答案。     
你正在混淆带有decaration的typedef。 如果要声明具有依赖类型的typedef,则需要使用typename关键字:
typedef typename vector<T>::const_iterator iter
iter A = a.begin( );
iter B = b.begin( );
BTW,即使没有typedef,也需要typename。     

要回复问题请先登录注册