我想知道以下matlab习语最有效的c++实现是什么。
假设我在 matlab 中有 3 个向量,x,y 和 idx。
x = [13,2,5.5,22,107]
y = [-3,100,200]
idx = [1,2,5]
我想用 y 的内容替换 x 的位置 1,2 和 5。在matlab我做
x[idx] = y
在 c++ 中执行此操作的最佳方法是什么?
Armadillo库可能是最接近的,因为它的目标之一是让习惯 Matlab 的人更容易。
这是一个简短的示例(并且uvec
是无符号整数向量的 typdef)
// set four specific elements of X to 1
uvec indices;
indices << 2 << 3 << 6 << 8;
X.elem(indices) = ones<vec>(4);
显然,右侧可以是与索引相同维度的任何其他向量。
但是很少有语言强加的限制是您无法克服的:
[
循环似乎很简单,尽管可以使用辅助函数使其更简单。
// helper function to get the size of an array
template<typename T, size_t S>
constexpr size_t size(T (&)[S])
{
return S;
}
// loop
for (size_t i = 0; i < size(idx); ++i) x[idx[i]] = y[i];
当然,在这里你应该检查它y
是否足够大:
如果你想在非常基本的 C++ 中使用它(没有优雅的奖品)试试这个:
double x[] = { 13.0, 2.0, 5.5, 22.0, 107.0 };
double y[] = { -3.0, 100.0, 200.0 };
size_t idx[] = { 1, 2, 5 };
for ( size_t i = 0; i < sizeof(x)/sizeof(double); ++i )
cout << x[i] << " ";
cout << endl;
// Make a mutable copy of x
double x1[ sizeof(x)/sizeof(double) ];
std::copy( x, x + sizeof(x)/sizeof(double), x1 );
// The transformation
for ( size_t i = 0; i < sizeof(idx)/sizeof(double); ++i )
x1[idx[i]] = y[i];
for ( size_t i = 0; i < sizeof(x)/sizeof(double); ++i )
cout << x1[i] << " ";
cout << endl;
请注意非常漂亮,但它确实提供了以下内容:
13 2 5.5 22 107
-3 100 5.5 22 200
(请注意,我假设索引从 1 而不是 0 in 开始idx
)