我知道已经有几个问题了,我相信我已经尝试了所有建议的解决方案,但仍然遇到问题。我的内部向量是大小为3的行,我需要根据列0对外部向量进行排序,列0是向量中每行的第一个元素,然后是1 ,2。
代码:
vector < vector<double> > ftstPrices;
for (int i=0; i<n;i++)
{
vector <double> stepPrices;
for (j=0 ;j<1259;j++)
{
stepPrices.push_back(.......);
}//end of for price simu
stepPrices.erase(stepPrices.begin(),stepPrices.begin()+251);
stepPrices.erase(stepPrices.begin()+1,stepPrices.begin()+252);
stepPrices.erase(stepPrices.begin()+2,stepPrices.begin()+757);
ftstPrices.push_back(stepPrices);//push the inner vector into outer
/* this is the tricky part im having issues with */
sort(ftstPrices.begin(),ftstPrices.end(), [](const vector<double>&x,const vector<double>&y) {
return stepPrices[0]<stepPrices[0]
});
}错误:
C:\CPP\Projects\monteCarlo\simulations.cpp|68|error: 'stepPrices' is not captured|
C:\CPP\Projects\monteCarlo\simulations.cpp|68|error: 'stepPrices' is not captured|
C:\CPP\Projects\monteCarlo\simulations.cpp|68|error: expected ';' before '}' token|
c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\stl_algo.h||In instantiation of 'void 根据请求输入和输出示例column1 column2 column3
83.0201 13.3513 24.56
15.8398 43.3559 9.66
28.9211 38.8552 32.33
22.8481 45.9503 8.45
6.20375 16.6046 11.95StepPrices是添加到ftstPrices向量中的行
排序后的向量应如下所示的column1 Column2 Column3
6.20375 13.3513 8.45
15.8398 16.6046 9.66
22.8481 38.8552 11.95
28.9211 43.3559 24.56
83.0201 45.9503 32.33发布于 2014-08-24 17:00:38
使用Boost.Range很容易做到这一点。
我们需要的是一个随机访问范围(对于sort()),它的每个元素都映射到原始范围的相应元素中的一个元素。所以我们可以写一个转换函数:
template<std::size_t N>
struct select_element
{
template<class T>
typename T::reference operator()(T& source) const { return source[N]; }
};请注意,operator ()返回对容器的value_type的引用,以启用修改。
现在我们可以将其与transformed range适配器一起使用:
using boost::adaptors::transformed;
std::vector<std::vector<double>> input = /* ... */;
boost::sort(input | transformed(select_element<0>()));
boost::sort(input | transformed(select_element<1>()));
boost::sort(input | transformed(select_element<2>()));Demo。
如果不能使用Boost,在概念上最简单的方法是将每列收集到单独的向量中,对列进行排序,然后从排序的列重新生成行。
发布于 2020-01-11 19:04:48
您可以使用老的std::sort(),定义一个比较器:
struct DataRowComparatorByColumnIndex {
bool operator() ( const std::vector<double>& row1,
const std::vector<double>& row2 ) {
return row1[m_columnIndex] < row2[m_columnIndex] ;
}
uint m_columnIndex;
};然后使用它对表/数据帧/矩阵进行排序:
std::vector< std::vector<double> > table = /* ... */;
// Sort the data by given column.
DataRowComparatorByColumnIndex dataRowComparatorByColumnIndex;
dataRowComparatorByColumnIndex.m_columnIndex = 2; //sort by 3rd column
std::sort( result.begin(), result.end(), dataRowComparatorByColumnIndex );https://stackoverflow.com/questions/25457927
复制相似问题