Reputation: 11
I got a dilemma about creating an alias of variable and need your kind help.
Purpose
My function takes two vector, but I want to ensure that that vector variable "a" will refer to the longer one. At the same time, I don't want to copy the vector. So, I use the reference to create an alias, but I got a dilemma.
Situation 1
The variable can not be seen since the variable is in if clause, but I need the if clause to know which is longer.....
vector<float> conv(const vector<float> &operand1, const vector<float> &operand2){
if (operand1.size() < operand2.size()){
const vector<float> &a = operand2;
const vector<float> &b = operand1;
}
else{
const vector<float> &a = operand1;
const vector<float> &b = operand2;
}
Situation 2
Declare the reference outside the if clause. Unfortunately, the reference has to be initialized when declared. However, I need the if clause to know which operand to declare it as.
vector<float> conv(const vector<float> &operand1, const vector<float> &operand2){
const vector<float> &a;
const vector<float> &b;
if (operand1.size() < operand2.size()){
&a = operand2;
&b = operand1;
}
else{
&a = operand1;
&b = operand2;
}
Is there any way getting around this?? Thank you a lot.
Upvotes: 1
Views: 428
Reputation: 595981
You can use pointers instead of references:
vector<float> conv(const vector<float> &operand1, const vector<float> &operand2)
{
const vector<float> *a;
const vector<float> *b;
if (operand1.size() < operand2.size())
{
a = &operand2;
b = &operand1;
}
else
{
a = &operand1;
b = &operand2;
}
// use *a and *b as needed ...
}
Upvotes: 0
Reputation: 875
Is this you want:
vector<float> conv(const vector<float>& op1, const vector<float>& op2) {
const vector<float> &a = op1.size() < op2.size() ? op2 : op1; // the longer one
const vector<float> &b = op1.size() < op2.size() ? op1 : op2; // the other
...
}
Upvotes: 1