存储一个函数的向量和std::string的一个向量的向量是什么类型
What is the type of a vector that stores a vector of one function and one vector of std::string
我现在正在尝试解决问题,但我不能,我需要为此找到一个类型
(python)
def fn1(hello: list[str]) -> None:
pass
mv = [(fn1, ("1", "hello", "12", "no")), (fn1, ("w", "ufewef", "1ee", "no"))] # any size
mv
的 C++ 类型是什么? (不管它是否可变)
我试过 std::vector<std::vector<std::string, std::function>>
但它会抛出错误,有没有办法做到这一点,或者必须使用两个向量?
这些类型变得复杂,所以为了使它们更短,我将首先定义几个类型别名:
using StringVec = std::vector<std::string>;
using StringVecFunc = std::function<void(const StringVec&)>;
现在您的数据容器的类型可以是以下任何一种:
using T1 = std::vector<std::tuple<StringVecFunc, StringVec>>;
using T2 = std::vector<std::pair<StringVecFunc, StringVec>>;
struct StringVecFuncAndArgs {
StringVecFunc func;
StringVec args;
};
using T3 = std::vector<StringVecFuncAndArgs>;
最大的区别在于您如何访问包含一个函数和一个字符串容器(如 python 元组)的事物的元素。对于 std::tuple
,您使用 std::get<0>(t)
和 std::get<1>(t)
或 std::get<StringVecFunc>(t)
和 std::get<StringVec>(t)
。对于 std::pair
,您使用 p.first
和 p.second
。对于自定义结构,您使用 data.func
和 data.args
.
tuple
解决方案可能是 Python 元组思想的最直接翻译。如果不需要在大量代码中使用 pair
,它会快速而简单。自定义结构解决方案需要的工作最多,但可以让您为成员提供有用的名称。
我的程序使用 stringVec
struct 声明 vector<string> hello
和 returns void stringVecFunc
,以打印 hello
.
的值为例
struct stringVec {
vector<string> hello;
void stringVecFunc();
};
void stringVec::stringVecFunc() {
for (auto &x: hello) cout << x << "\t";
cout << endl;
}
之后一个vector负责存储stringVec
类型的数据,这样:
stringVec stringVec1;
stringVec1.hello = {"hi", "hello", "hi", "hello"};
vector<stringVec> vec;
你可以运行一个完整的例子here
我现在正在尝试解决问题,但我不能,我需要为此找到一个类型
(python)
def fn1(hello: list[str]) -> None:
pass
mv = [(fn1, ("1", "hello", "12", "no")), (fn1, ("w", "ufewef", "1ee", "no"))] # any size
mv
的 C++ 类型是什么? (不管它是否可变)
我试过 std::vector<std::vector<std::string, std::function>>
但它会抛出错误,有没有办法做到这一点,或者必须使用两个向量?
这些类型变得复杂,所以为了使它们更短,我将首先定义几个类型别名:
using StringVec = std::vector<std::string>;
using StringVecFunc = std::function<void(const StringVec&)>;
现在您的数据容器的类型可以是以下任何一种:
using T1 = std::vector<std::tuple<StringVecFunc, StringVec>>;
using T2 = std::vector<std::pair<StringVecFunc, StringVec>>;
struct StringVecFuncAndArgs {
StringVecFunc func;
StringVec args;
};
using T3 = std::vector<StringVecFuncAndArgs>;
最大的区别在于您如何访问包含一个函数和一个字符串容器(如 python 元组)的事物的元素。对于 std::tuple
,您使用 std::get<0>(t)
和 std::get<1>(t)
或 std::get<StringVecFunc>(t)
和 std::get<StringVec>(t)
。对于 std::pair
,您使用 p.first
和 p.second
。对于自定义结构,您使用 data.func
和 data.args
.
tuple
解决方案可能是 Python 元组思想的最直接翻译。如果不需要在大量代码中使用 pair
,它会快速而简单。自定义结构解决方案需要的工作最多,但可以让您为成员提供有用的名称。
我的程序使用 stringVec
struct 声明 vector<string> hello
和 returns void stringVecFunc
,以打印 hello
.
struct stringVec {
vector<string> hello;
void stringVecFunc();
};
void stringVec::stringVecFunc() {
for (auto &x: hello) cout << x << "\t";
cout << endl;
}
之后一个vector负责存储stringVec
类型的数据,这样:
stringVec stringVec1;
stringVec1.hello = {"hi", "hello", "hi", "hello"};
vector<stringVec> vec;
你可以运行一个完整的例子here