[英]c++ problem with vector push_back
更新:以下代碼給我一個錯誤
Graph.cpp:在函數'std :: ostream&operator <<(std :: ostream&,const Graph&)':Graph.cpp:43:錯誤:傳遞'const std :: map>,std :: less,std ::分配器>>>>作為'_Tp&std :: map <_Key,_Tp,_Compare,_Alloc> :: operator [](const _Key&)的'this'參數[帶有_Key = long int,_Tp = std :: vector> ,_Compare = std :: less,_Alloc = std :: allocator>>>]'丟棄限定符Graph.cpp:44:錯誤:傳遞'const std :: map>,std :: less,std :: allocator>>> >'作為'_Tp&std :: map <_Key,_Tp,_Compare,_Alloc> :: operator [](const _Key&)['_Key = long int,_Tp = std :: vector>,_Compare = std的'this'參數:: less,_Alloc = std :: allocator>>>]'丟棄限定符make [2]: * [build / Debug / GNU-MacOSX / Graph.o]錯誤1
class Graph {
public:
Graph();
Graph(const Graph& orig);
virtual ~Graph();
void clear();
void rgg(lint, double);
bool is_directed() { return directed; }
friend ostream& operator<< (ostream&, const Graph&);
private:
map< lint, vector<lint> > adjList;
vector< pair<double, double> > xy;
double radius;
MTRand Rand;
bool directed;
};
void Graph::rgg(lint n, double r) {
radius = r; directed = false;
clear();
for(lint i = 0; i < n; i++)
xy.push_back(pair<double, double>(Rand.rand(), Rand.rand()));
}
ostream& operator<< (ostream& os, const Graph& inGraph) {
for(lint i = 0; i < inGraph.nodes; i++) {
os << i << " ";
if( inGraph.adjList.find(i) != inGraph.adjList.end() ) {
for(lint idx = 0; idx < (inGraph.adjList[i]).size(); idx++ )
os << inGraph.adjList[i].at(idx) << " ";
}
os << endl;
}
}
先感謝您,
我懷疑您的意思是蘭特而不是MTRand:
Rand.rand()
MTRand是類型的名稱。 蘭德是您創建的實例的名稱。
只是一個猜測,但您嘗試過嗎
xy.push_back(pair<double, double>(MTRand.rand(), MTRand.rand())
根據xy的減法?
編輯:似乎OP更改了它的代碼,現在我的答案不再與新問題匹配。 不過,希望我的回答是有用的。
問題的原因是地圖的operator[]
是可變操作(如果鍵不存在,它將被添加到地圖中)。
您將必須使用find()
返回的迭代器:
map< lint, vector<lint> >::const_iterator it = inGraph.adjList.find(i);
if (it != inGraph.adjList.end();
for(lint idx = 0; idx < it->size(); idx++ )
os << it->at(idx) << " ";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.