向量push_back的c ++问题

时间:2011-01-15 09:28:02

标签: c++ class stl map

更新: 以下代码给出了错误

  

Graph.cpp:在函数'std :: ostream&   operator<<(std :: ostream&,const   Graph&)':Graph.cpp:43:错误:传递   'const std :: map>,   性病::少,   std :: allocator> > > >”如   '_Tp&的'这个'论点   std :: map< _Key,_Tp,_Compare,   _Alloc> :: operator [](const _Key&)[with _Key = long int,_Tp = std :: vector>,_ Compare =   std :: less,_Alloc =   std :: allocator> > >]”   丢弃限定符Graph.cpp:44:   错误:传递'const std :: map>,   性病::少,   std :: allocator> > > >”如   '_Tp&的'这个'论点   std :: map< _Key,_Tp,_Compare,   _Alloc> :: operator [](const _Key&)[with _Key = long int,_Tp = std :: vector>,_ Compare =   std :: 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;
    }
}

提前谢谢你,

3 个答案:

答案 0 :(得分:4)

我怀疑你的意思是兰德而不是MTRand:

Rand.rand()

MTRand是该类型的名称。 Rand是您创建的实例的名称。

答案 1 :(得分:4)

只是一个猜测,但你试过吗

 xy.push_back(pair<double, double>(MTRand.rand(), MTRand.rand())

根据xy的解释?

编辑:似乎OP改变了它的代码,现在我的答案不再符合新问题了。不过,希望我的回答很有用。

答案 2 :(得分:1)

问题的原因是地图的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) << " ";