【问题标题】:C++ Templates and STL vector problemC++模板和STL向量问题
【发布时间】:2011-01-18 13:35:26
【问题描述】:

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

我正在尝试创建类

#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

【问题讨论】:

  • 为什么在vector&lt;T&gt;::iterator A;前面加上“typename”?
  • @Kiril: 因为vector&lt;T&gt;::iterator 是从属名称?
  • 在下一行中,你只使用一次类型名A,你会得到什么?此外,由于这是一个模板类,并且将位于头文件中 - 永远不要将任何 using namespace 声明放在头文件中。
  • @Mephane:模板定义有时属于.cpp 文件,如果模板仅用于此文件。
  • @Alexandre - 哎呀,我的错,对。 10x

标签: c++ templates stl iterator typename


【解决方案1】:

使用

typename vector<T>::const_iterator A = a.begin();
typename vector<T>::const_iterator B = b.begin();

因为ab 是常量引用,所以调用begin 的常量版本,它返回const_iterator,而不是iterator。你不能将const_iterators 分配给iterators,就像你不能将pointers-to-const 分配给指针一样。

【讨论】:

  • @Nim 你不能将const_iterators 分配给iterators,这就像将一个指向 const 的指针分配给一个指针。
  • (顺便说一句,typename vector&lt;T&gt;::const_iterator A = a.begin(); 有什么问题?)
  • @sbi:没什么,我会在我的代码中写的。但是 OP 使用了赋值运算符,而不是复制构造。
  • @Alexandre,我知道! :) 我的问题是,你为什么要这样做?换句话说,为什么要在 const 容器上使用非 const 迭代器?啊,我看到你编辑了答案!!! :D 好吧,让我原来的问题看起来很愚蠢!?!
  • @Alexandre:这是 OP 的问题,而不是你的问题。我应该在这个问题上问它,真的。
【解决方案2】:
typename vector<T>::iterator A;

应该是

typename vector<T>::const_iterator A;

B 也一样

更新

我的 C++ 技能生疏了,但是

因为传递给 merge 的两个 vectors 是 const 引用,所以您不能使用标准迭代器来移动它们,因为标准迭代器允许您修改向量的内容。因此,您必须使用const_iterator,这将不允许您修改矢量内容。

抱歉,如果我的 C++ Fu 没有达到标准,我记得有足够多的 C++ 来解决问题,但在 . . .哇 7 年(真的那么长吗?烦死我了,但我老了)。

正如我所说,如果您能提供更好的解释,请随时编辑此答案。

【讨论】:

  • 删除了我的,你秒杀我! :)
  • 我认为typename 这里是强制性的(除非你碰巧使用Visual Studio,它与typename 不兼容)
  • 这里的答案说明了您需要做什么。如需进一步参考,请查看此处(尤其是示例,因为它显示了如何使用迭代器的简单案例):cplusplus.com/reference/stl/vector/begin
  • 应该是typename vector&lt;T&gt;::const_iteratorector&lt;T&gt;::const_iterator 显然取决于模板参数。 (当您怀疑时:理论上,是否有针对某些 Tst::vector 的专门化,其中 iterator 是静态数据成员的名称?如果是,则需要 typename。)
【解决方案3】:

您将 typedef 与声明混淆了。

如果你想声明一个依赖类型的 typedef,那么你需要使用 typename 关键字:

typedef typename vector<T>::const_iterator iter
iter A = a.begin( );
iter B = b.begin( );

顺便说一句,即使没有 typedef,也需要 typename。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    相关资源
    最近更新 更多