使用多维std :: initializer_list [英] Using multidimensional std::initializer_list

查看:113
本文介绍了使用多维std :: initializer_list的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对C ++中多维std :: intializer_list的使用有疑问.我有一个Matrix类,并且希望能够像这样初始化它:

I have a question about the use of multidimensional std::intializer_list in C++. I have a Matrix class, and I want to be able to initialize it like this:

Matrix<int, 3, 3> m({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});

我现在拥有的构造函数采用二维初始化器列表的参数,但是编译器不喜欢我的使用方式.这是代码:

The constructor that I have now takes an argument of a two-dimensional initializer list, but the compiler doesn't like how I'm using it. Here's the code:

template<typename T, unsigned int rows, unsigned int cols>
Matrix<T, rows, cols>::Matrix(std::initializer_list<std::initializer_list<T> > set)
{
    std::vector<std::initializer_list<T> > setVec = set;
    std::vector<std::vector<T> > v;

    for (std::vector<std::initializer_list<T> >::iterator i = setVec.begin(); i != setVec.end(); i++)
    {
        v.push_back(std::vector<T>(*i));
    }

    this->matrixData = new T*[rows];

    for (unsigned int i = 0; i < rows; i++)
    {
        this->matrixData[i] = new T[cols];

        for (unsigned int j = 0; j < cols; j++)
        {
            this->matrixData[i][j] = v[i][j];
        }
    }
}

这是错误:

..\/utils/Matrix.h:138:7: error: need 'typename' before 'std::vector<std::initializer_list<_CharT> >::iterator' because 'std::vector<std::initializer_list<_CharT> >' is a dependent scope

如何消除该错误?有没有一种方法可以对其进行重组,这样我就不必制作一个初始化列表或其他东西的丑陋矢量了?

How do I get rid of that error? Is there a way to restructure it so I don't have to make that ugly vector of an initializer list or something?

推荐答案

是的,如错误消息所示,您需要在此处编写typename:

Yes, as the error message says, you need to write typename here:

typename std::vector<std::initializer_list<T>>::iterator i = setVec.begin();

这是因为iterator是从属名称.阅读此内容以获取详细说明:

It is because iterator is a dependent name. Read this for detail explanation:

如果您的编译器支持C ++ 11引入的auto,则可以编写以下代码:

If your compiler supports auto introduced by C++11, then you could write this:

auto i = setVec.begin();

这是更好的语法.由于您已经在使用C ++ 11功能(例如std::initializer_list),因此应该在容易使用的任何地方开始使用auto.

which is much better syntax. Since you're already using C++11 feature such as std::initializer_list, you should start using auto wherever it makes your life easy.

这篇关于使用多维std :: initializer_list的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆