How to store solution into vector

Hi everyone. I'm new to C++. Seeking for advise. I would like to ask. I got error when I want to store a solution into a vector. I don't know how can I fix the error. How can I store a fitness value into a vector. Thank you for the help.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Finding maximum & minimum value of obj function
	double maxElement = *max_element(obj_function.begin(), obj_function.end());
	double minElement = *min_element(obj_function.begin(), obj_function.end());
	cout << "Max Element: " << maxElement << '\n';
	cout << "Min Element: " << minElement << '\n';
	cout << endl;

	// Calculate fitness and mapping fitness value of each plant
	cout << "Fitness :" << endl;
	vector<double> fitnessFX;
	const double diff = maxElement - minElement;
	if (diff > 0)
	{
		for (size_t i = 0; i < obj_function.size(); i++)
		{
			double fitness = (maxElement - obj_function[i]) / diff;		//calculate fitness value
			fitnessFX = fitness;
			cout << start_node[i] << "	" << fitnessFX << endl;
			cout << endl;
		}
Line 17:

fitnessFX.push_back(fitness);
Or fitnessFX.emplace_back( fitness );

We know how many elements will be in fitnessFX and therefore we can preallocate correct amount of memory for it:
1
2
3
4
5
6
if ( diff > 0 ) {
    fitnessFX.reserve( obj_function.size() );
    for ( size_t i = 0; i < obj_function.size(); i++ ) {
        double fitness = (maxElement - obj_function[i]) / diff;
        fitnessFX.push_back( fitness );
    }

or
1
2
3
4
5
6
if ( diff > 0 ) {
    fitnessFX.resize( obj_function.size() );
    for ( size_t i = 0; i < obj_function.size(); i++ ) {
        double fitness = (maxElement - obj_function[i]) / diff;
        fitnessFX[i] = fitness;
    }
Topic archived. No new replies allowed.