Hi everyone. I need some advice. How can i split the following vector. For example, row 1 until 10 will be in first column and row 11 until row 20 will be in second column.
I have a vector (namely as new_obj_function):
246.187
223.655
221.221
208.876
208.805
208.725
207.946
206.678
202.659
185.133
246.072
244.842
223.49
210.24
215.256
246.259
246.945
245.677
252.333
208.988
I need to split it into 2d vector (10 value for each column) as follow:
246.187 246.072
223.655 244.842
221.221 223.49
208.876 210.24
208.805 215.256
208.725 246.259
207.946 246.945
206.678 245.677
202.659 252.333
185.133 208.988
But, after code it. I got a wrong solution as follow:
246.187 223.655
221.221 208.876
208.805 208.725
207.946 206.678
202.659 185.133
246.072 244.842
223.49 210.24
215.256 246.259
246.945 245.677
252.333 208.988
// Create a vector that contains n generations of total distance @ Z-value
vector<vector<double>> new_total_distance(population_size);
for (size_t i = 0; i < population_size; i++)
{
// Get the i-th inner vector from the outer vector and fill it
vector<double> & inner_vector = new_total_distance[i];
for (size_t j = 0; j < generation; j++)
{
inner_vector.push_back(new_obj_function[generation * i + j]);
}
}
for (size_t i = 0; i < new_total_distance.size(); i++)
{
for (size_t j = 0; j < new_total_distance[i].size(); j++)
{
cout << new_total_distance[i][j] << " ";
}
cout << "\n";
}
cout << "\n";
#include <iostream>
#include <vector>
int main()
{
usingnamespace std;
using Column = std::vector<double>;
const size_t num_columns = 2;
vector<double> raw_data { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
size_t size_per_column = raw_data.size() / num_columns; // 10 / 2 == 5
vector<Column> columned_data(num_columns,
vector<double>(size_per_column));
for (size_t i = 0; i < num_columns; i++)
{
for (size_t j = 0; j < size_per_column; j++)
{
columned_data[i][j] = raw_data[i * size_per_column + j];
}
}
for (size_t j = 0; j < size_per_column; j++)
{
for (size_t i = 0; i < num_columns; i++)
{
// (would be more efficient to print each column together)
cout << columned_data[i][j] << ' ';
}
cout << '\n';
}
}
1 6
2 7
3 8
4 9
5 10
Assumes the number of columns divides the number of elements in the raw data.
Perhaps that can help. I don't see an obvious problem with your original post's code excerpt, but like I said I didn't attempt to run it since I couldn't.