Skip to content

Is there a way to optimize/reduce this sequence of assigning variables? (C++)

An answer to this question on Stack Overflow.

Question

I was wondering if there's a way to optimize/reduce this logic? As the number of the variables increases, the number of the parameters increases as well, which can make the code a bit messy.

.h file

class ClassA
{
public:
	ClassB type1_1;
	ClassB type1_2;
	ClassB type1_3;
	// ... There can be more than this
	ClassB type2_1;
	ClassB type2_2;
	ClassB type2_3;
	// ... There can be more than this
	void SetType1(ClassB a, ClassB b, ClassB c);
	void SetType2(ClassB a, ClassB b, ClassB c);
	__forceinline vector<ClassB> GetListofType1() { return list_type1; }
	__forceinline vector<ClassB> GetListofType2() { return list_type2; }
private:
	vector<ClassB> list_type1;
	vector<ClassB> list_type2;
};

.cpp file

// ... As the number of type1 variables increases, the number of parameters increases
void ClassA::SetType1(ClassB a, ClassB b, ClassB c)
{
	type1_1 = a;
	type1_2 = b;
	type1_3 = c;
	list_type1.push_back(a);
	list_type1.push_back(b);
	list_type1.push_back(c);
}
// ... As the number of type2 variables increases, the number of parameters increases
void ClassA::SetType2(ClassB a, ClassB b, ClassB c)
{
	type2_1 = a;
	type2_2 = b;
	type2_3 = c;
	list_type2.push_back(a);
	list_type2.push_back(b);
	list_type2.push_back(c);
}

Answer

Use initializer lists:

#include <cassert>
#include <vector>
struct ClassB { };
class ClassA {
public:
  static constexpr int list_type1_len = 3;
  inline void SetType1(const std::vector<ClassB>& set_type_1){
      assert(set_type_1.size()==3);
      list_type1 = set_type_1;
  }
  inline std::vector<ClassB>& GetListofType1() { return list_type1; }
private:
  std::vector<ClassB> list_type1;
};
int main(){
    ClassA a;
    a.SetType1({ClassB(), ClassB(), ClassB()});
    return 0;
}