[英]Vector Iterator and insert function using typedef, C++
我正在嘗試在 c++ 中實現堆 class。我在插入成員 function 中遇到問題。當我嘗試創建迭代器時,我嘗試了兩種方法,但由於某種原因都給了我錯誤。 這是我的第一種方法:
#ifndef Heap_hpp
#define Heap_hpp
#include <stdio.h>
#include <vector>
#include <iterator>
#include <string>
#include <iostream>
typedef int elementType;
class Heap{
private:
std::vector<elementType> myVecrtor;
int mySize = 1; //The minimum size is 1 since the first element is a dummy.
public:
Heap();
void insert(elementType const item);
};
//implementation of first method
void Heap::insert(elementType const item){
typename std::vector<elementType> :: iterator it = mySize;/* I got the error
in this line*/
myVecrtor.insert(it, item);//insert after first element(dummy)
mySize++;
}
錯誤:
No viable conversion from 'int' to 'typename std::vector<int>::iterator' (aka '__wrap_iter<int *>') Candidate constructor not viable: no known conversion from 'int' to 'std::__wrap_iter<int *>::iterator_type' (aka 'int *') for 1st argument; take the address of the argument with &
如果我遵循建議(在項目之前添加“&”),它會在同一行中給出下一個錯誤:
Calling a private constructor of class 'std::__wrap_iter<int *>'
這是我的第二種方法:
void Heap::insert(elementType const item){
auto it = mySize;//iterator
myVecrtor.insert(it, item)//here I got the error
mySize++;
}
錯誤:
No matching member function for call to 'insert'
起初我以為這是因為該項目不是 const 但它也沒有用。
在我的主體中,我只是創建了 class 的一個實例並調用了這個方法。 我不知道這兩種方法有什么問題。 任何幫助,將不勝感激。
對於初學者,此聲明中的關鍵字typename
typename std::vector<elementType> :: iterator it = mySize;
是多余的。 去掉它。
std::vector<elementType> :: iterator it = mySize;
沒有將 integer 轉換為迭代器的構造函數。 所以上面的聲明沒有意義。
看來您正在嘗試將 append 一個新值添加到向量的末尾。 如果是這樣,那么就寫
myVecrtor.push_back(item);
mySize++;
如果你要在指定的 position 中插入一個新值,那么寫
#include <iterator>
//...
myVecrtor.insert( std::next( std::begin( myVecrtor ), mySize ), item);
mySize++;
注意這個聲明
std::vector<elementType> myVecrtor;
聲明一個沒有任何虛擬元素的空向量。 因此,要使用迭代器向向量添加新元素,您必須編寫
myVecrtor.insert( std::begin( myVecrtor ), item);
迭代器不是int
。 mySize
是一個int
。
auto it = mySize;//iterator
評論說這行是胡說八道。 it
不是迭代器。
typename std::vector<elementType> :: iterator it = mySize;
此行嘗試將int
轉換為迭代器。 編譯器會抱怨,因為你不能那樣做。
我不確定您的代碼試圖對mySize
做什么,所以我無法更正它。
可以通過調用myVecrtor.begin()
生成迭代器。 在對myVecrtor
進行任何可能的調整大小操作(例如insert
)后,此類迭代器將無效。
計算向量中元素的數量是沒有意義的。 myVecrtor.size()
將為您維護它。 在最后插入只需要調用push_back(int)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.