【问题标题】:Initializing 2d vector in C++ compile error: wrong intepretation of compiler在 C++ 编译错误中初始化 2d 向量:编译器的错误解释
【发布时间】:2021-03-05 22:27:15
【问题描述】:

我有以下代码。

constexpr int w=50;
constexpr int h=50;
struct Canvas {
    std::vector<std::vector<char>> net( w, std::vector<char>(h) );
    void clear(const char clear_char = ' ') {
        for (int i = 0; i < net.size(); ++i)
            for (int j = 0; j < net[i].size(); ++j)
                net[i][j] = clear_char;
    }
    void draw_circle(const Brush& brush, const int cx, const int cy, const int r){
        static int c = 0;
        for (double i = 0; i <= 6.28; i += 0.02) {
            int y = round(0.54*r * sin(i))+cy;
            int x = round(r * cos(i)) + cx;
            if (c >= 0 && c <= 1)
                net[y][x] = brush.outline;

            else
                net[y][x] = brush.fill;
        }
        if (c != 0 && r == 0) {
            c = 0;
        }
        else if(brush.fill!='\0'){
            ++c;
            draw_circle(brush, cx, cy, r - 1);
        }
    }
};

我想创建一个 2D 字符向量(wxh 维度),但我的编译器指出了以下错误:

E0757: variable w is not a type name.

如何解决?

【问题讨论】:

  • @KarenBaghdasaryan 这很好用。您能否提供使用该行的完整代码。
  • 我提供了
  • (...) 不允许对类范围内的成员进行初始化。您必须使用 {...}= ...,例如std::vector&lt;std::vector&lt;char&gt;&gt; net = std::vector&lt;std::vector&lt;char&gt;&gt;( w, std::vector(h) );.
  • @HolyBlackCat 非常感谢。
  • 顺便说一句,以浮点相等测试结束的循环不是一个好主意,因为可能存在微小的方向错误,使其过早停止一次迭代

标签: c++ vector initialization


【解决方案1】:

您的数组大小是固定的,因此可以使用std::array&lt;&gt;

constexpr int w=50;
constexpr int h=50;
struct Canvas {
std::array<std::array<char,w>,h> net;
void clear(const char clear_char = ' ') {
    for (int i = 0; i < h; ++i)
        for (int j = 0; j < w; ++j)
            net[i][j] = clear_char;
...

【讨论】:

  • 是的,但它没有解释为什么 OP 的代码不起作用。
  • 我同意,但我使用 std::vector 以便稍后更改向量的大小。
猜你喜欢
  • 2019-07-10
  • 2018-05-01
  • 2011-09-02
  • 2011-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多