-1
麻煩
我有一個迭代器類,它定義了++運算符:錯誤C2676;具有限定++運算符的二叉搜索樹類在C++
template<typename T>
class Iterator : public std::iterator<std::forward_iterator_tag, T>
{
public:
Iterator(TreeNode<T>* p)
{
if (p == nullptr)
current = -1; // The end
else
{
// Get all the elements in inorder
treeToVector(p);
current = 0;
}
}
Iterator operator++()
{
current++;
if (current == v.size())
current = -1; // The end
return *this;
}
T& operator*()
{
return v[current];
}
bool operator==(const Iterator<T>& iterator) const
{
return current == iterator.current;
}
bool operator!=(const Iterator<T>& iterator) const
{
return current != iterator.current;
}
private: int current;
vector<T> v;
void treeToVector(TreeNode<T>* p)
{
if (p != nullptr)
{
treeToVector(p->left);
v.push_back(p->element);
treeToVector(p->right);
}
}
};
我有一個TestBSTIterator文件,以確保它的工作原理:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <algorithm>
#include "BST.h"
using namespace std;
string toUpperCase(string& s)
{
for (size_t i = 0; i < s.length(); i++)
s[i] = toupper(s[i]);
return s;
}
int main()
{
// Create a binary search tree for strings
BST<string> tree;
// Add elements to the tree
tree.insert("America");
tree.insert("Canada");
tree.insert("Russia");
tree.insert("France");
// Traverse a binary tree using iterators
for (Iterator<string> iterator = tree.begin();
iterator != tree.end(); iterator++)
{
cout << toUpperCase(*iterator) << " ";
}
cout << endl << "Min element is " <<
*min_element(tree.begin(), tree.end()) << endl;
cout << "Max element is "
<< *max_element(tree.begin(), tree.end()) << endl;
return 0;
}
當我嘗試運行TestBSTIterator我得到以下錯誤:
錯誤C2676:二進制「++」:「遊標」不定義這種操作或轉換到類型接受的預先規定的操作
1>使用
1> [
1> T =的std :: string
1>]
我有 「操作符++」 功能的迭代器類,所以我不太瞭解問題所在。我試着簡單地用一個泛型類型實現函數,即迭代器運算符++(){...}但是沒有效果。
好抓。感謝那! – so8857