关于类:向量push_back的c ++问题

c++ problem with vector push_back

更新:下面的代码给出了一个错误

Graph.cpp: In function 'std::ostream&
operator<<(std::ostream&, const Graph&)': Graph.cpp:43: error: passing 'const std::map >,
std::less,
std::allocator > > > >' as
'this' argument of '_Tp&
std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = long int, _Tp = std::vector >, _Compare =
std::less, _Alloc =
std::allocator > > >]'
discards qualifiers Graph.cpp:44:
error: passing 'const std::map >,
std::less,
std::allocator > > > >' as
'this' argument of '_Tp&
std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = long int, _Tp = std::vector >, _Compare =
std::less, _Alloc =
std::allocator > > >]'
discards qualifiers make[2]: *
[build/Debug/GNU-MacOSX/Graph.o] Error
1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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;
    }
}

事先谢谢你,


只是猜测一下,但你试过了吗?

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

根据xy的下倾?

编辑:似乎操作程序改变了它的代码,现在我的答案不再匹配新问题了。不过,希望我的回答有用。


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

1
Rand.rand()

mtrand是类型的名称。rand是您创建的实例的名称。


问题的原因是map的operator[]是一个可变操作(如果键不存在,它将被添加到map中)。

您必须使用从find()返回的迭代器:

1
2
3
4
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) <<"";