我想在 C 中B從一個矩陣創建一個矩陣。A
第一列A是距離D1,第二列是距離D2。MatrixB復制 的相同列(和行)A,除非A其中發生D2-D1=delta超過閾值。在這種情況下, 的行在A中分成兩行B。
我寫了一個演算法,但問題是它給出了segmentation fault. 有人可以幫忙,為什么會這樣?
std::vector<float> newD1(10), newD2(10);
float box=5.;
int j=0;
for(auto i=0;i<D1.size();i ){
float delta=D2[i]-D1[i];
if (delta>box){ //break row i in two rows: j and j 1
//first half of row i goes in row j
newD1[j]=D1[i];
newD2[j]=(D1[i] D2[i])/2.;
//second half of row i goes in j 1
D1[j 1]=(D1[i] D2[i])/2.;
D2[j 1]=D2[i];
j=j 2; //we skip two row because we break up the original row in 2 rows
}
else{
newD1[j]=(D1[i]);
newD2[j]=D2[i];
j=j 1; //we skip one row because the original row is unchanged
}
}
這里我給你一個矩陣A和的例子B;我還在delta矩陣的每一行旁邊指定。
矩陣A:
#D1 D2 delta
|0 5 | 5
A= |5 15 | 10 }--> exceed the threshold, delta>5. Must break in 2 rows in `B`
|15 17 | 2
B創建將第二行分成兩行,因為 delta>5 :
#D1 D2 delta
|0 5 | 5
B= |5 10 | 5 }--> created from row #2 of `A`. `D2` is midpoint between`D1` and `D2` in row #2 in `A`
|10 15 | 5 }--> created from row #2 of `A`. `D1` is midpoint between`D1` and `D2` in row #2 in `A`
|15 17 | 2
EDIT:
What if I want to recursively break up the rows (e.g. suppose that at row #2 in A, delta>3*box, meaning that I need to break up that row in 3 rows in B). Any suggestions?
uj5u.com熱心網友回復:
1.您可以使用push_back來避免尺寸定義
2.你更新了 D1 和 D2 而不是 newD1 和 newD2
#include <vector>
#include <iostream>
using namespace std;
int main()
{
std::vector<float> D1 = { 0,5,15 };
std::vector<float> D2 = { 5,15,17 };
std::vector<float> newD1, newD2;
float box = 5.;
for (auto i = 0; i < D1.size(); i ) {
float delta = D2[i] - D1[i];
if (delta > box) { //break row i in two rows: j and j 1
//first half of row i goes in row j
newD1.push_back(D1[i]);
newD2.push_back((D1[i] D2[i]) / 2.);
//second half of row i goes in j 1
newD1.push_back ((D1[i] D2[i]) / 2.);
newD2.push_back (D2[i]);
}
else {
newD1.push_back(D1[i]);
newD2.push_back(D2[i]);
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/427556.html
