如何将函数中的stl列表传递为C 中的参数

How to pass the stl list in the function as parameter in C++

本文关键字:参数 stl 函数 列表      更新时间:2023-10-16

我有一个基类,例如:

class Base
{
public:
    virtual void fun() const =0;
};
class Derived: public Base 
{
    virtual void fun()
    {
        //implemtation of fun
    }
};

我有一个全球结构:

struct Mystruct {
    int a;
    char *b;
} MYSTRUCT;

然后我将结构添加到向量:

List  = new MYSTRUCT;
vector<MYSTRUCT*> SS;
SS.push_back(List);

如何将此矢量传递到娱乐函数并访问函数中的结构?

您似乎对此的含义感到困惑:

struct Mystruct
{
int a;
char *b;
}MYSTRUCT;

这是一个称为Mystruct 的结构的声明,Mystruct的实例称为MYSTRUCT。因此,当您创建std::vectorsstd::lists持有这些结构时,您需要使用 type 作为模板参数:

std::vector<Mystruct> v0; // vector holding 0 Mystructs

如果您想要持有指针的向量,则需要

std::vector<Mystruct*> v1;

这根本不会编译,因为MYSTRUCT不是类型:

std::vector<MYSTRUCT*>

这样:

class Base
{
public:
    virtual void fun(const std::vector<Mystruct*>& list) const =0;
};
class Derived:public Base 
{
public:
    virtual void fun(const std::vector<Mystruct*>& list)
    {
        //implemtation of fun
    }
};

但是您的示例表明您可能会遇到其他问题,了解如何设计C 类(例如,您不需要使用此C,例如cluct定义语法,带有C )。