I am trying to figure a thing out right now and I can't, I need to find a type for this
(python)
def fn1(hello: list[str]) -> None:
pass
mv = [(fn1, ("1", "hello", "12", "no")), (fn1, ("w", "ufewef", "1ee", "no"))] # any size
what is a C type for mv
? (doesn't matter if it's mutable or not)
I tried std::vector<std::vector<std::string, std::function>>
but it kelp throwing an error, is there a way to do it or will have to use two vectors?
CodePudding user response:
These types get complicated, so to make them shorter I'll first define a couple of type alias:
using StringVec = std::vector<std::string>;
using StringVecFunc = std::function<void(const StringVec&)>;
Now the type of your data container could be any of these:
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>;
The big difference is how you access elements of the thing holding one function and one string-container (like the python tuples). For std::tuple
you use std::get<0>(t)
and std::get<1>(t)
or std::get<StringVecFunc>(t)
and std::get<StringVec>(t)
. For std::pair
you use p.first
and p.second
. For the custom struct you use data.func
and data.args
.
The tuple
solution is maybe the most direct translation from the idea of a Python tuple. The pair
is quick and easy if it doesn't need to be used from a lot of code. The custom struct solution takes the most work, but lets you give helpful names to the members.
CodePudding user response:
My program uses a stringVec
struct that declares a vector<string> hello
and a function that returns void stringVecFunc
, which to use as an example prints the values of hello
.
struct stringVec {
vector<string> hello;
void stringVecFunc();
};
void stringVec::stringVecFunc() {
for (auto &x: hello) cout << x << "\t";
cout << endl;
}
After this, a vector is responsible for storing data of type stringVec
by this way:
stringVec stringVec1;
stringVec1.hello = {"hi", "hello", "hi", "hello"};
vector<stringVec> vec;
you can run a complete example here