我正在努力解决这个问题,而且,这真的让我很恼火。我有一个函数可以将数组或 vector 转换为复数 vector ,但是,我不知道该函数如何能够同时接受双数组和双 vector 。我试过使用模板,但这似乎不起作用。模板
template<typename T>
vector<Complex::complex> convertToComplex(T &vals)
{
}
Value::Value(vector<double> &vals, int N) {
};
Value::Value(double *vals, int N) {
};
我希望的是这样的:
int main()
{
double[] vals = {1, 2, 3, 4, 5};
int foo = 4;
Value v(vals, foo); // this would work and pass the array to the constructor, which would
// then pass the values to the function and covert this to a
// vector<complex>
}
我也可以对 vector 做同样的事情..我不知道模板是否是正确的方法。
最佳答案
你可以让你的函数和构造函数成为一个带有两个迭代器的模板:
template<typename Iterator>
vector<Complex::complex> convertToComplex(Iterator begin, Iterator end)
{
}
class Value
{
public:
template <Iteraror>
Value(Iterator begin, Iterator end)
{
vector<Complex::complex> vec = comvertToComplex(begin, end);
}
....
};
然后
double[] vals = {1, 2, 3, 4, 5};
Value v(std::begin(vals), std::end(vals));
std::vector<double> vec{1,2,3,4,5,6,7};
Value v2(v.begin(), v.end());
我省略了
foo
因为我不太清楚它的作用是什么。关于c++ - 在不同的数据类型之间交替,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17457529/