[英]c++ convert vector<pair<double,double>> to double*, double*?
Is there a way to get the contiguous memory of the ".first" and ".second" of vector<pair<double,double>>
? 有没有办法获取
vector<pair<double,double>>
“ .first”和“ .second”的连续内存? What I mean is: 我的意思是:
void func(int N, double* x, double* y)
{
for (int i = 0; i < N; ++i)
//do something to x[i] and y[i]
}
For the above function I have a vector<pair<double,double>> point
rather than vector<double> x, y
. 对于上述函数,我有一个
vector<pair<double,double>> point
而不是vector<double> x, y
。 I'm guessing this is not possible. 我猜这是不可能的。 If I had a vector x,y then I could do x.data() and y.data() of course.
如果我有向量x,y,那么我当然可以做x.data()和y.data()。
The memory layouts of std::vector<std::pair<double, double>> xy
and std::vector<double> x,y
are different. std::vector<std::pair<double, double>> xy
和std::vector<double> x,y
的内存布局不同。 If func
is part of a third-party library you can not change, you are bound to 如果
func
是第三方库的一部分,您不能更改,那么您必然
a) call func
a couple of times with N=1
or (quick an dirty) a)用
N=1
或(快速进行肮脏的)几次调用func
auto xy = std::vector<std::pair<double, double>> {
{0,0}, {42,0}, {0, 42}, {42, 42}
};
for (auto& [x,y] : xy) { // or for (auto& p : xy) func(1, p.first, p.second)
func(1, &x, &y);
}
b) convert xy
to x
and y
b)将
xy
转换为x
和y
template <typename T, typename S>
auto convert(const std::vector<std::pair<T,S>>& xy)
{
auto xs = std::vector<T>{};
auto ys = std::vector<S>{};
xs.reserve(xy.size());
ys.reserve(xy.size());
for (auto& [x,y] : xy) {
xs.push_back(x);
ys.push_back(y);
}
return std::make_pair(xs, ys);
}
int main()
{
auto xy = std::vector<std::pair<double, double>> {
{0,0}, {42,0}, {0, 42}, {42, 42}
};
auto [x, y] = convert(xy);
func(xy.size(), x.data(), y.data());
}
c) simply change the defintions of xy
to x
and y
. c)只需将
xy
的定义更改为x
和y
。
If you can change func
, I propose to refactor such that you can call the inner loop and rewrite it for iterators (or ranges). 如果可以更改
func
,我建议进行重构,以便您可以调用内部循环并将其重写为迭代器(或范围)。 That way you could use it with projections on std::pair
s. 这样,您可以将其与
std::pair
的投影一起使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.