vector 的 C++ Vector 搞乱了我

标签 c++

如果我将此代码放入 .cpp 文件中并运行它,它运行得很好:

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


using namespace std;

typedef vector<int> row;
typedef vector<row> myMatrix;

void main()
{
    //cout << endl << "test" << endl;
    myMatrix mat(2,2);

    mat[0][1] = 2;

    cout << endl << mat[0][1] << endl;
}

但是,如果我像这样用 .h 文件制作一个 .h 和一个 .cpp 文件,它会给我一大堆错误。

#ifndef _grid_
#define _grid_

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

using namespace std;

typedef vector<int> row;
typedef vector<row> myMatrix;

class grid
{
    public:

        grid();

        ~grid();

        int getElement(unsigned int ri, unsigned int ci);

        bool setElement(unsigned int ri, unsigned int ci, unsigned int value);


    private:

        myMatrix sudoku_(9,9);
};

#endif

这些是我得到的一些错误:

warning C4091: 'typedef ' : ignored on left of 'int' when no variable is declared
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

最佳答案

您需要将 vector 限定为 std::vector

它在 .cpp 文件中有效,因为您使用 using namespace std;(不要在头文件中使用 using namespace)。

此外,您对成员变量的声明不正确。它应该只是:

myMatrix sudoku_;

如果你想设置它的维度,你需要在构造函数中这样做。

关于 vector 的 C++ Vector 搞乱了我,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2718689/

相关文章:

c++ 类,这可行,但有人可以改进它,使其符合标准/编码实践

c++ - 剩余堆大小

c++ - 运行时错误打印字符串,即使它在函数中工作正常

c++ - 创建 string_view 元素数组会引发错误 : unable to find string literal operator ‘operator""sv’ with

c++ - Firemonkey:缩小文本字体以适应 TLabel

c++ - 检查 std::wstring 是 null 还是空

c++ - 程序忽略 while 循环内容,当强制访问循环内的方法时崩溃

c++ - OpenGL 相机 - 在使用 SetCursorPos(x,y) 时移动相机而不使其快速返回;?

C++如何使用经纬度确定时区

c++ - 为什么 glScaled(1, 1, 5) 会改变 glVertex3d(1, 1, 0) 的光照?