c++ - 如何解决 ‘std::list<int>*’ 到 ‘std::list<int> [0]’ 分配中的不兼容类型?

标签 c++ c++11

这是一个简单的c++图形算法

#include <iostream>
#include <string>
#include <list>
#include <vector>

using namespace std;

class Graph {
    public:
        Graph(int v = 1):
            vertexs(v), edges(0) {
                adj = new list<int>[vertexs];
            }

        void test_put() {
            int iter_cnt = 0;
            for (int i = 0; i < vertexs; i++) {
                for (int j = 0; j < 3; j++) {
                    adj[i].push_back(iter_cnt++);
                }
            }
        }

        void test_print() {
            list<int>:: iterator iter;
            for (int i = 0; i < vertexs; i++) {
                for (iter = adj[i].begin(); iter != adj[i].end(); iter++) {
                    cout << *iter << "->";
                }
                cout << "###" << endl;
            }
        }

    private:
        int vertexs;
        int edges;
        list<int> adj[];
};

int main() {
    Graph g(10);
    g.test_put();
    g.test_print();
}

有一个错误

ian@ubuntu:~/tmp$ g++ wgraph.cpp -o wg
wgraph.cpp: In constructor ‘Graph::Graph(int)’:
wgraph.cpp:12:44: error: incompatible types in assignment of ‘std::list<int>*’ to ‘std::list<int> [0]’

我是一名java程序员,我不知道如何在c++中制作合适的构造函数。

最佳答案

这个声明

list<int> adj[];

生成一个零长度数组,而不是您稍后可以指定其大小的数组。

虽然你不能直接做你想做的事,但 C++ 标准库提供了一个很好的方法来解决这个问题:使用 vector<list<int> >解决问题。

像这样声明 vector :

vector<list<int> > adj;

像这样初始化它:

Graph(int v = 1)
:  vertexs(v), edges(0), adj(vertexs) {
}

其余用法与数组相同 - 您可以使用方括号访问 vector 的元素。当然现在你的adj可以根据需要进行扩展 - 您所要做的就是调用 push_back添加更多元素。

关于c++ - 如何解决 ‘std::list<int>*’ 到 ‘std::list<int> [0]’ 分配中的不兼容类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19750001/

相关文章:

python - C++ 输出与 Python 不同的消息(从串口读取)

c++ - OpenCV/C++ 程序比它的 numpy 对应程序慢,我该怎么办?

c++ - 如何制作文件中所有不同单词的字母顺序列表以及每个单词的使用次数?

c++ - For vs While 用于查找链表中的最后一项

c++ - g++ 不能静态链接 libmongcxx(r3.0.2) 但动态链接有效

C++ 延长 && 的生命周期

c++ - 一次包含已在 main.obj 中定义的 .h 函数

c++ - 将带有占位符的绑定(bind)结果存储在 std::function 中

c++ - 隐式转换运算符

c++ - 在 1_54 中破坏了 boost 变体?