【问题标题】:Why can't I access the vector? [closed]为什么我无法访问矢量? [关闭]
【发布时间】:2017-11-18 21:56:56
【问题描述】:

我目前正在尝试访问这样定义的向量:

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

using namespace std;
template<class T>
class file
{
    public:
        typedef vector<vector<T> > buffer;
};


int main()
{
    file<double> test;
    cout << test.buffer.size() << endl;


    std::vector<pair<string, file<double> > > list_of_files;

    for (const auto& [name, file] : list_of_files)
    {
        cout << file.buffer.size() << endl;
    }

}

我收到的错误消息是像我目前正在做的那样对buffer 进行范围是无效的?但为什么它无效?我看不出它应该是什么原因?

我在 for 循环中试图在 buffer 的内部和外部向量之间进行迭代,但是由于我无法确定它的范围,所以我无法访问?我如何访问它?

【问题讨论】:

  • buffer 不是向量。它是一个 typedef,这意味着您可以稍后使用 buffer myBuffer; 声明一个向量作为 vector&lt;vector&lt;T&gt;&gt; myBuffer; 的简写。但是你的类还没有向量。

标签: c++ class templates vector structured-bindings


【解决方案1】:

错误的原因是代码将buffer 声明为vector&lt;vector&lt;T&gt;&gt; 的新类型。如果你想让buffer 成为file 的成员,你可以这样做:

template<class T>
class file
{
public:
    std::vector<std::vector<T>> buffer;
};

更改后,main() 应该可以正确编译。

【讨论】:

    猜你喜欢
    • 2012-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 2018-05-25
    相关资源
    最近更新 更多