I have a question, its a bit hard to discribe it so be easy on me please.
I have two classes, A and B, class A have a private member- vector:
class A
{
private:
struct complex
{
int x;
vector< int > y;
};
vector< complex > m_resultVector; // <---- the private member
public:
void getPointerToVector( vector< complex >::iterator it )
{
it = m_resultVector.begin();
}
};
I need to get access (only read) from class B, to this m_resultVector;
, I could write a get
function but m_resultVector
is very long vector and I don't want to copy the entire vector to a new one, I want to send its pointer. also the important part- I need class B cannot change the content of m_resultVector
class B
{
struct complex
{
int x;
vector< int > y;
};
void functionOf_B()
{
A class_A;
vector< complex >::iterator p_resultVector;
class_A.getPointerToVector(p_resultVector); // <------ compilation error here
// some reading from the content of p_resultVector
}
};
when I try to compile it, I get the error:
cannot convert parameter 1 from 'std::_Vector_iterator<_Myvec>' to 'std::_Vector_iterator<_Myvec>'
so basically, I have to questions-
complex
struct is defined in both classes. const iterator
on class B, so it will be read only? I'm not sure ... That is because A::complex
and B::complex
are different types (with same content, but that does not matter). So that vector<A::complex>
and vector<B::complex>
are different. Move definition of struct complex
outside A
and B
.
Also there are more issues in your code. A::getPointerToVector
does nothing, because it copies input vector iterator to temporary one, assigns a value to it and after return from that function, everything is lost. Using this approach, you would have to pass vector<complex>::iterator
as reference (thus vector<complex>::iterator&
).
I would rather write a method in A
like this
const vector<complex>& get_vector() const
{
return m_resultVector;
}
I this way, you can doo this.
void foo()
{
A class_A;
// do something with A
const vector<complex>& p_result = class_A.get_vector();
// now you are holding whole vector and you can call methods
// defined as const (which does not modify that vector)
p_result.begin();
p_result.at(0);
p_result.end();
}
Zereges solution seems good. But I understand you do not want to return vector. I could not come up with any solution other than below.
In Class A:
void getPointerToVector(int position, int &var,vector<int>& o_Vec)
{
vector<complex>::iterator itr;
complex c;
c = m_resultVector.at(position);
var = c.x;
o_Vec = c.y;
}
In class B :
void functionOf_B()
{
A class_A;
int aVar;
std::vector<int> vec;
class_A.getPointerToVector(2, aVar, vec);
// some reading from the content of p_resultVector
}
I am not sure how efficient and complex this is. I would suggest better to use Zereges solution
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.