[英]Unable to access elements of Array in c++
我有以下情況。
class A
{
public:
std::vector<double *> getData()
{
return test;
}
void setData()
{
double * data = new double[1];
data[0] = 1;
double data1[] = {1};
test.push_back(data); // Pushing first element as double *
test.push_back(data1); // Pushing second element as double[]
}
private:
std::vector<double*> test;
};
class B
{
public :
void displaySum(A *a)
{
std::vector<double *> data = a->getData();
double sum = 0.0;
for(int i = 0; i < data.size(); i++)
{
printf("Data at %d : %f \n", i, data[i][0]); // Getting 0 for second element
sum = sum + data[i][0];
}
printf("Sum is : %f \n", sum);
}
};
int main()
{
A *a = new A();
a->setData();
B *b = new B();
b->displaySum(a);
return 0;
}
在類A中,具有成員變量std :: vector test,並且我用double *和double []填充向量,但是在輸出中,第二個元素的值為0。 但是,就像在A類setData方法中一樣,添加了double [] = {1}。 所以在輸出中我應該在第二個元素上得到1。 請幫忙 。 難道我做錯了什么。 請給我解釋一下。 謝謝!
OUTPUT ::
Data at 0 : 1.000000 // First Element
Data at 1 : 0.000000 // Second Element ->should be 1
Sum is : 1.000000 // Sum should be 2
double data1[] = {1};
是setData()
本地對象,在setData
退出並且vector內的內容懸空之后被銷毀。
采用 :
double *data1 = new double (1.0);
再次在setData()
中看到2
當您推送data1
,您實際上是在將指針推送到data1
的第一個元素(此時存在隱式轉換)。
由於data1
是該函數的本地函數,因此setData
返回后,該指針將立即失效。
您還需要為此使用動態分配,或將vector
存儲在vector
。
根據我的解釋,代碼應該能夠添加數組以及單個double數據,因此可以代替使用vector<double *>
來使用vector <double>
。
#include <iostream>
#include <vector>
using namespace std;
class A
{
public:
std::vector<double> getData()
{
return test;
}
void setData()
{
double data = 1.00;
double data1[] = {1.00};
test.push_back(data); // Pushing first element as double
// Pushing second element as double[]
for(int i = 0; i < 1 /* Provide array size here */; i ++)
{
test.push_back(data1[i]);
}
}
private:
std::vector<double> test;
};
class B
{
public :
void displaySum(A *a)
{
std::vector<double> data = a->getData();
double sum = 0.0;
for(int i = 0; i < data.size(); i++)
{
printf("Data at %d : %f \n", i, data[i]); // Getting 0 for second element
sum = sum + data[i];
}
printf("Sum is : %f \n", sum);
}
};
int main()
{
A *a = new A();
a->setData();
B *b = new B();
b->displaySum(a);
return 0;
}
輸出:
向量中的第二個元素是垃圾值,同時調用b-> displaySum(a),因為第二個元素引用了局部變量
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.