[英]Median of multiple vectors of double (c++, vector < vector<double> >)
[英]Access Vector of Vectors <double*>
我在訪問vector <vector <* double >>中保存的雙精度數時遇到麻煩。 我正在讀取.txt文件,並將存儲在其中的值(應該構成矩陣)保存在我的向量載體中。
vector <vector<double*>> HypMean;
ifstream myFile;
myFile.open(nameOfFile);
if (myFile.is_open() && myFile.good()) {
string line;
while(getline(myFile, line)){ //Get line-by-line in file
istringstream buffer(line);
string value;
int numLoop = 0;
vector <double*> tempVector;
while (getline (buffer, value, ',')){ //Get character by character in line
istringstream valuebuffer(value);
tempVector.push_back(new double[1]);
valuebuffer >> *(tempVector.back() + numLoop);
cout << *(tempVector.back() + numLoop) << " ";
numLoop++;
}
HypMean.push_back(tempVector);
cout << endl;
}
myFile.close();
}
這是我的功能,我想我保存的是正確的值,因為當我在創建“ tempVector”的同時打印它時就可以了。
0.014872 0.078519 0.071838 -0.10371
-0.16741 -0.0063904 0.0018366 0.21238
0.13796 -0.29323 0.23489 -0.074523
但是,當我嘗試訪問整個對象(HypMean)時,我不知道該怎么做。 我沒有運氣就嘗試了以下方法:
for (int x=0; x<3; x++){
for (int y=0; y<4; y++){
cout << *(HypMean[x][y]) << " ";
}
cout<<endl;
}
0.014872 -6.27744e+66 -6.27744e+66 -6.27744e+66
-0.16741 -6.27744e+66 -6.27744e+66 -6.27744e+66
0.13796 -6.27744e+66 -6.27744e+66 -6.27744e+66
有什么想法嗎? 我應該更改什么才能正確訪問它? 提前致謝!
問題是在這些行中,您正在寫入和讀取一些隨機存儲器:
valuebuffer >> *(tempVector.back() + numLoop);
cout << *(tempVector.back() + numLoop) << " ";
在對push_back
的調用之后, tempVector.back()
是對tempVector
中最后一個元素的引用,該元素是指向double
大小為1的數組中的第一個元素的指針。如果numLoop
指針添加numLoop
,則會得到一些隨機的內存關閉了double
數組的末尾。
您可以通過將以下行更改為“修復”它:
valuebuffer >> *tempVector.back();
cout << *tempVector.back() << " ";
但是,沒有充分的理由來分配大小為1的double
的數組,而不是std::vector<std::vector<double*>>
。 僅使用std::vector<std::vector<double>>
會更簡單,您可以使用類似以下的內容:
tempVector.push_back(0.0);
valuebuffer >> tempVector.back();
然后,您可以使用以下命令讀取2D矢量:
for (int x=0; x<3; x++){
for (int y=0; y<4; y++){
cout << HypMean[x][y] << " ";
}
cout<<endl;
}
還是更好
for (const auto& v : HypMean){
for (auto value : v) {
cout << value << " ";
}
cout<<endl;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.