C++ 模板和 STL vector 问题

标签 c++ templates stl iterator typename

我在简单的事情上需要帮助

我正在尝试创建类

#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();

因为 ab 是 const 引用,begin 的 const 版本被调用,它返回一个 const_iterator,而不是迭代器。您不能将 const_iterator 分配给 iterator,就像您不能将 pointers-to-const 分配给指针一样。

关于C++ 模板和 STL vector 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4724672/

相关文章:

C++ 为输入类型选择模板输出类型

c++ - 我应该避免哪些 C++ 陷阱?

c++ - 标准容器是否提供一些缓存功能?

c++ - 如何拆分要分配给 C++ 中具有不同索引的单独变量的字符串?

c++ - 截止时间计时器到期,现在怎么办?

c++ - 在 C++ 中使用无序 _map 将整数转换为字符

c++ - 接受 N 个转换为相同类型的参数

c# - 使用 Handlebars 和 Mandrill-dotnet -library 的 mandrill 中的每个循环

c++ - 序列容器的重新分级删除功能

c++ - R 检查不喜欢 std :cout (C++)