3

我有以下二维向量/矩阵XY如下向量:

std::vector<double> Y; 
unsigned int ctr=2;
std::vector<std::vector<double> >X(ctr,Y);

我现在想创建 X 的转置,即 Xtrans,所以声明如下

std::vector<std::vector<double> >Xtrans(Y,ctr);

但它给了我以下编译错误:

test.cpp:128:58: error: no matching function for call to ‘std::vector<std::vector<double> >::vector(std::vector<double>&, unsigned int&)’
/usr/include/c++/4.5/bits/stl_vector.h:241:7: note: candidates are: std::vector<_Tp, _Alloc>::vector(const std::vector<_Tp, _Alloc>&) [with _Tp = std::vector<double>, _Alloc = std::allocator<std::vector<double> >, std::vector<_Tp, _Alloc> = std::vector<std::vector<double> >]
/usr/include/c++/4.5/bits/stl_vector.h:227:7: note:                 std::vector<_Tp, _Alloc>::vector(std::vector::size_type, const value_type&, const allocator_type&) [with _Tp = std::vector<double>, _Alloc = std::allocator<std::vector<double> >, std::vector::size_type = unsigned int, value_type = std::vector<double>, allocator_type = std::allocator<std::vector<double> >]
/usr/include/c++/4.5/bits/stl_vector.h:215:7: note:                 std::vector<_Tp, _Alloc>::vector(const allocator_type&) [with _Tp = std::vector<double>, _Alloc = std::allocator<std::vector<double> >, allocator_type = std::allocator<std::vector<double> >]
/usr/include/c++/4.5/bits/stl_vector.h:207:7: note:                 std::vector<_Tp, _Alloc>::vector() [with _Tp = std::vector<double>, _Alloc = std::allocator<std::vector<double> >]

如何正确声明 Xtrans?

4

4 回答 4

2

除了其他人已经说过的关于修复代码的内容之外,我想评论一下使用vector<vector<double> >矩阵表示,这种表示非常低效,几乎从来都不是你想要的。我的一个同事曾经使用这种风格继承了一个代码。使用适当的索引摆弄函数将其转换为简单vector<double>,性能提高了30倍。抵制诱惑。

您可能想查看许多可用的 C++ 矩阵库之一(例如eigenuBlasmtl4等等;还有很多其他的)。

于 2012-04-30T15:43:29.497 回答
1

我认为这里有两个问题-第一个是您可能误解了std::vector's 的构造方式,以及当您这样做时

std::vector<std::vector<double> >Xtrans(Y,ctr); 

它正在生成编译器错误,因为没有与您的声明匹配的构造函数。

std::vector(即你用来声明的那个)的构造函数之一X是这样声明的:

explicit vector ( size_type n, const T& value= T(), const Allocator& = Allocator() );

所以当你这样做(ctr, Y)的时候效果很好——因为你告诉编译器你想创建一个std::vector大小ctr,不管值Y是什么。(在你的情况下Y是一个空的std::vector<double>- 所以你有一个ctr条目向量,其中每个条目都是一个空的std::vector<double>

所以简单地交换ctrY希望你能得到一个转置std::vector在这里是行不通的。

第二个问题是你如何实际转置这些值。您实际上需要找出一种算法来执行 X 的转置,然后将这些值推送到 Xtrans。转置值与实际构造向量是不同的。最有可能的是,您的算法类似于-construct XTrans,然后迭代“X and insert values intoXTrans”。

于 2012-04-30T15:41:08.063 回答
0

只是为了使代码编译你可以声明Xtrans如下

std::vector<double> Y;
unsigned int ctr=2;
std::vector<std::vector<double> >X(ctr,Y);
std::vector<double> ctr_vector(2);
std::vector<std::vector<double> >Xtrans(Y.size(),ctr_vector);

但是,您必须填充 Xtrans 才能将其用作 X 的转置版本

于 2012-04-30T15:39:31.360 回答
0

您似乎误解了std::vector. 在这里查看更多信息

调用std::vector<std::vector<double> >X(ctr,Y)具有创建ctr多个副本Y并将其存储到 X 中的效果。因此,从根本上讲,它仍然是一个一维对象,X只是在X您的每个索引处返回另一个.std::vectorY

因此,您以后的语法std::vector<std::vector<double> >Xtrans(Y,ctr)与 type 的任何构造函数都不匹配std::vector。您不会像在 NumPy 或 Matlab 中那样构建二维数组。

您可能也想看看这个链接。可能对您来说最好的事情是编写自己的转置函数,手动将条目放入循环中的新数组中。

于 2012-04-30T15:40:02.340 回答