【问题标题】:c++ problem with vector push_back向量push_back的c ++问题
【发布时间】:2011-06-09 14:09:13
【问题描述】:

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

Graph.cpp:在函数 'std::ostream& 运算符, 标准::少, std::allocator > > > >' 为 '_Tp& 的 'this' 参数 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& 的 'this' 参数 std::map<_key _tp _compare _alloc>::operator[](const _Key&) [with _Key = long int, _Tp = std::vector >, _Compare = std::less, _Alloc = std::allocator > > >]' 丢弃限定符 make[2]: * [构建/调试/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;
    }
}

提前谢谢你,

【问题讨论】:

  • 您有析构函数和复制构造函数,但我没有看到复制赋值运算符。 Why?
  • 你为什么完全改变了这个问题?现在已经发布的答案都没有任何意义,这将完全混淆未来阅读该问题的任何人。如果您需要进一步的帮助,请恢复您的更改并发布一个新问题。

标签: c++ class stl map


【解决方案1】:

只是猜测,但你试过了吗

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

根据xy的declation?

编辑:似乎 OP 更改了它的代码,现在我的答案与新问题不再匹配。不过,希望我的回答有用。

【讨论】:

    【解决方案2】:

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

    你必须使用从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) << " ";
    

    【讨论】:

      【解决方案3】:

      我怀疑你指的是 Rand 而不是 MTRand:

      Rand.rand()
      

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

      【讨论】:

        猜你喜欢
        • 2023-03-04
        • 1970-01-01
        • 1970-01-01
        • 2013-03-28
        • 1970-01-01
        • 1970-01-01
        • 2011-04-19
        • 2014-09-13
        • 2016-11-16
        相关资源
        最近更新 更多