[英]How do I get elements into a nested vector with an initializer list c++
I have a Matrix class which contains a vector inside a vector as data within it.我有一个矩阵 class ,其中包含一个向量内的向量作为其中的数据。 I would like to be able to insert elements through initializer lists.我希望能够通过初始化列表插入元素。
An example of this would be the following:这方面的一个例子如下:
#include <vector>
int main(void) {
std::vector<std::vector<int>> v = {
{ 1, 2, 3, 4, 5 },
{ 6, 7, 8, 9, 10 }
};
}
It should also be noted that the vectors that I am using within the Matrix class are a custom vector class that I have written.还应该注意的是,我在矩阵 class 中使用的向量是我编写的自定义向量 class。 I have found a way to use initializer lists to add elements to the vector, but I do not know how to do the same with nested initializer lists, since the initializer lists do not provide subscripts.我找到了一种使用初始化列表向向量添加元素的方法,但我不知道如何对嵌套初始化列表执行相同操作,因为初始化列表不提供下标。
I know the size of the outer initializer list (in the above example it is two), but I don't know how to get the size of the second initializer list.我知道外部初始化列表的大小(在上面的示例中是两个),但我不知道如何获取第二个初始化列表的大小。
Here is a snippet of my code so far.到目前为止,这是我的代码片段。
Matrix.h矩阵.h
template<class type>
class Matrix {
private:
Vector<Vector<type>> data;
public:
Matrix() {}
Matrix(std::initializer_list<std::initializer_list<type>> init_list) {
/* Get the data */
}
}
Moreover, how does the std::vector class take in a potentially infinite amount of initializer lists and sort them out?此外,std::vector class 如何接收可能无限数量的初始化列表并将它们排序?
I would like to be able to insert elements through initializer lists.我希望能够通过初始化列表插入元素。 ...I know the size of the outer initializer list (in the above example it is two), but I don't know how to get the size of the second initializer list. ...我知道外部初始化列表的大小(在上面的示例中是两个),但我不知道如何获取第二个初始化列表的大小。
Perhaps I misunderstand you, but the code snippet below should give you a start.也许我误解了你,但下面的代码片段应该让你开始。 It prints the sizes of the outer and inner initializer lists, along with the elements, and compiles and runs fine in C++11, according to clang++ anyway.根据 clang++ 的说法,它打印外部和内部初始化列表的大小以及元素,并在 C++11 中编译和运行良好。
// ...
Matrix(const std::initializer_list<const std::initializer_list<type>> & init_list) {
cout << "vector of " << init_list.size() << " vectors" << endl;
for (const auto & inner_list : init_list) {
cout << inner_list.size() << " elements: " << endl;
for (const auto & m : inner_list) {
cout << m << ",";
}
cout << endl;
}
}
// ...
Matrix<int> M { { 1, 2 }, { -1, 2 } };
Moreover, how does the std::vector class take in a potentially infinite amount of initializer lists and sort them out?此外,std::vector class 如何接收可能无限数量的初始化列表并将它们排序?
I'm not sure I understand what you mean here.我不确定我明白你在这里的意思。 If I understand the question, then I think the snippet above answers it.如果我理解了这个问题,那么我认为上面的片段可以回答它。 If I don't, please elaborate in the comments & I can try to address it.如果我不这样做,请在评论中详细说明,我可以尝试解决它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.