How to relocate an element in one array in C++ - c++
I took this interview question and I failed, so I'm here to not fail again!
I have an array of int with size 16 and a 5 < givenIndex < 10.
I have to take the element in this index a print every possible array (there are 16) by moving the element at givenIndex through every position in array and pushing rest of elements.
For example:
int array[16] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
int givenIndex = 6;
Since array[givenIndex] = 7, I need to move 7 to every possible position and print that array.
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
[7,1,2,3,4,5,6,8,9,10,11,12,13,14,15,16]
[1,7,2,3,4,5,6,8,9,10,11,12,13,14,15,16]
[1,2,7,3,4,5,6,8,9,10,11,12,13,14,15,16]
And that's for 16 cases.
What I was trying was:
for(int i = 0;i<16;i++){
array[i] = array[indexInsercion]
if (i<indexInsert){
//right shift
array[i] = array[i+1]
}else if(i == indexInsert){
//no shift
}else{
//left shift
array[i] = array[i-1]
}
}
Can I get some help?
We can only guess what the interviewer expected to see. If I was the interviewer I would like to see that you keep things simple. This is code I think one can expect to be written from scratch in an interview situation:
#include <iostream>
#include <array>
template <size_t size>
void print_replaced(const std::array<int,size>& x,size_t index){
for (int i=0;i<size;++i){
for (int j=0;j<i;++j) {
if (j == index) continue;
std::cout << x[j] << " ";
}
std::cout << x[index] << " ";
for (int j=i;j<size;++j) {
if (j == index) continue;
std::cout << x[j] << " ";
}
std::cout << "\n";
}
}
int main() {
std::array<int,16> x{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
print_replaced(x,6);
}
It is a first approach at the problem, with a loop that prints 16 different combinations of the array elements. Printing each line follows simple logic: We print all elements before the one that should be replaced, then the one that should be shuffled, then the remaining elements.
It is simple, but wrong. Its output is:
7 1 2 3 4 5 6 8 9 10 11 12 13 14 15 16
1 7 2 3 4 5 6 8 9 10 11 12 13 14 15 16
1 2 7 3 4 5 6 8 9 10 11 12 13 14 15 16
1 2 3 7 4 5 6 8 9 10 11 12 13 14 15 16
1 2 3 4 7 5 6 8 9 10 11 12 13 14 15 16
1 2 3 4 5 7 6 8 9 10 11 12 13 14 15 16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
1 2 3 4 5 6 8 7 9 10 11 12 13 14 15 16
1 2 3 4 5 6 8 9 7 10 11 12 13 14 15 16
1 2 3 4 5 6 8 9 10 7 11 12 13 14 15 16
1 2 3 4 5 6 8 9 10 11 7 12 13 14 15 16
1 2 3 4 5 6 8 9 10 11 12 7 13 14 15 16
1 2 3 4 5 6 8 9 10 11 12 13 7 14 15 16
1 2 3 4 5 6 8 9 10 11 12 13 14 7 15 16
1 2 3 4 5 6 8 9 10 11 12 13 14 15 7 16
There is one line that appears twice and the last line is missing.
As an interviewer I would not be surprised that the first attempt does not produce correct output. I don't care about that. Thats not a minus. What I would care about is how you react on that. Do you know the next steps? Do you have a strategy to fix the wrong output? Or do you just panic because you didn't manage to write the correct code on the first attempt? This is what I would like to check in an interview and then thats the end of the exercise. I want to ask more different questions rather than giving you the time to fix all mistakes and write correct well tested code, because I know that this takes more time than we have in the interview.
I'll leave it to you to fix the above code ;)
Here's a quick stab at it. Basically just keep track of where the given index should go and print it there as well as skip the original position it would be in.
#include <iostream>
int main()
{
int array[16] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16 };
int givenIndex = 6;
for (int p = 0; p <= 16; ++p)
{
if (p != givenIndex)
{
std::cout << "[";
for (int i = 0; i < 16; ++i)
{
if (i == p)
{
if (i > 0)
{
std::cout << ",";
}
std::cout << array[givenIndex];
}
if (array[i] != array[givenIndex])
{
if (i > 0 || p == 0)
{
std::cout << ",";
}
std::cout << array[i];
}
}
if (p == 16)
{
std::cout << "," << array[givenIndex];
}
std::cout << "]\n";
}
}
}
Output:
[7,1,2,3,4,5,6,8,9,10,11,12,13,14,15,16]
[1,7,2,3,4,5,6,8,9,10,11,12,13,14,15,16]
[1,2,7,3,4,5,6,8,9,10,11,12,13,14,15,16]
[1,2,3,7,4,5,6,8,9,10,11,12,13,14,15,16]
[1,2,3,4,7,5,6,8,9,10,11,12,13,14,15,16]
[1,2,3,4,5,7,6,8,9,10,11,12,13,14,15,16]
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
[1,2,3,4,5,6,8,7,9,10,11,12,13,14,15,16]
[1,2,3,4,5,6,8,9,7,10,11,12,13,14,15,16]
[1,2,3,4,5,6,8,9,10,7,11,12,13,14,15,16]
[1,2,3,4,5,6,8,9,10,11,7,12,13,14,15,16]
[1,2,3,4,5,6,8,9,10,11,12,7,13,14,15,16]
[1,2,3,4,5,6,8,9,10,11,12,13,7,14,15,16]
[1,2,3,4,5,6,8,9,10,11,12,13,14,7,15,16]
[1,2,3,4,5,6,8,9,10,11,12,13,14,15,7,16]
[1,2,3,4,5,6,8,9,10,11,12,13,14,15,16,7]
If the expectation is to just print the elements of array in the given order:
Keep the track of current index of array element to be print, say indx -
If the position of current element processing is equal to row number then
print the element at givenIndex.
If indx is equal to givenIndex skip it and print indx + 1 element, otherwise print element at indx and increase indx by 1.
Implementation:
#include <iostream>
#include <array>
int main() {
std::array<int, 16> array = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
std::size_t givenIndex = 6;
for (std::size_t i = 0, indx = 0; i < array.size(); indx = 0, ++i) {
std::cout << '[';
for (std::size_t j = 0; j < array.size(); ++j) {
if (j == i) {
std::cout << array[givenIndex] << ',';
continue;
}
if (indx == givenIndex) {
++indx;
}
std::cout << array[indx++] << ',';
}
std::cout << ']';
std::cout << '\n';
}
return 0;
}
Output:
# ./a.out
[7,1,2,3,4,5,6,8,9,10,11,12,13,14,15,16,]
[1,7,2,3,4,5,6,8,9,10,11,12,13,14,15,16,]
[1,2,7,3,4,5,6,8,9,10,11,12,13,14,15,16,]
[1,2,3,7,4,5,6,8,9,10,11,12,13,14,15,16,]
[1,2,3,4,7,5,6,8,9,10,11,12,13,14,15,16,]
[1,2,3,4,5,7,6,8,9,10,11,12,13,14,15,16,]
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,]
[1,2,3,4,5,6,8,7,9,10,11,12,13,14,15,16,]
[1,2,3,4,5,6,8,9,7,10,11,12,13,14,15,16,]
[1,2,3,4,5,6,8,9,10,7,11,12,13,14,15,16,]
[1,2,3,4,5,6,8,9,10,11,7,12,13,14,15,16,]
[1,2,3,4,5,6,8,9,10,11,12,7,13,14,15,16,]
[1,2,3,4,5,6,8,9,10,11,12,13,7,14,15,16,]
[1,2,3,4,5,6,8,9,10,11,12,13,14,7,15,16,]
[1,2,3,4,5,6,8,9,10,11,12,13,14,15,7,16,]
[1,2,3,4,5,6,8,9,10,11,12,13,14,15,16,7,]
If the expectation is to alter the order of elements in the array and then print the array:
First move the element at givenIndex to the 0th index of array and then -
Print array
In every iteration swap the current element with its next element in the array and print it.
Implementation:
#include <iostream>
#include <array>
void print_array (std::array<int, 16>& array) {
std::cout << '[';
for (std::size_t indx = 0; indx < array.size(); ++indx) {
std::cout << array[indx] << ',';
}
std::cout << ']';
std::cout << '\n';
}
void rearrange_array_elem (std::array<int, 16>& array, std::size_t givenIndx) {
// move the element at givneIndx to first position in array
for (std::size_t j = givenIndx; j > 0; --j) {
std::swap (array[j], array[j - 1]);
}
// print array
print_array (array);
for (std::size_t indx = 0; indx < array.size() - 1; ++indx) {
// swap current element with its next element
std::swap (array[indx], array[indx + 1]);
print_array (array);
}
}
int main() {
std::array<int, 16> array = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
std::size_t givenIndex = 6;
rearrange_array_elem (array, givenIndex);
return 0;
}
Output:
# ./a.out
[7,1,2,3,4,5,6,8,9,10,11,12,13,14,15,16,]
[1,7,2,3,4,5,6,8,9,10,11,12,13,14,15,16,]
[1,2,7,3,4,5,6,8,9,10,11,12,13,14,15,16,]
[1,2,3,7,4,5,6,8,9,10,11,12,13,14,15,16,]
[1,2,3,4,7,5,6,8,9,10,11,12,13,14,15,16,]
[1,2,3,4,5,7,6,8,9,10,11,12,13,14,15,16,]
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,]
[1,2,3,4,5,6,8,7,9,10,11,12,13,14,15,16,]
[1,2,3,4,5,6,8,9,7,10,11,12,13,14,15,16,]
[1,2,3,4,5,6,8,9,10,7,11,12,13,14,15,16,]
[1,2,3,4,5,6,8,9,10,11,7,12,13,14,15,16,]
[1,2,3,4,5,6,8,9,10,11,12,7,13,14,15,16,]
[1,2,3,4,5,6,8,9,10,11,12,13,7,14,15,16,]
[1,2,3,4,5,6,8,9,10,11,12,13,14,7,15,16,]
[1,2,3,4,5,6,8,9,10,11,12,13,14,15,7,16,]
[1,2,3,4,5,6,8,9,10,11,12,13,14,15,16,7,]
Related
how to build a two three series program in C++
i have this CS question that says: We will define a series two three to be a series whose first term is some natural number. If the value of the member number n in the series is x, then the value of the (n +1)th member in the series is: (x % 2 ==0) ? x/2 : x*3 +1. You must write a program that prints two or three series starting with the numbers 1 to twenty-five (not inclusive), but the creation of each series will stop when a value greater than a thousand or a value that has already appeared in a previous series is produced (and therefore the sub-series that was produced from this array onwards has already been produced). The value that is produced must be displayed again, thus stopping the production of the series. now the code i have written outputs a similar result to the solution output but it needs some changes in order to get the same exact result which i couldn't figure out, this is my code. #include <iostream> using std::cin; using std::cout; using std::endl; int main() { int array[25]; for (int i = 1; i < 25; i++) { int currentNum = i; int theNumAfter; bool occured = false; while (occured == false) { for (int i = 0; i <= 25; i++) { if (array[i] == currentNum) { occured = true; cout << endl; } } array[currentNum] = currentNum; cout << currentNum << " "; if (currentNum % 2 == 0) { theNumAfter = currentNum / 2; } else { theNumAfter = (3 * currentNum) + 1; } array[theNumAfter] = theNumAfter; cout << theNumAfter << " "; currentNum = theNumAfter; } } } the code doesn't take any input and there is only one right output which should be this: 1 4 2 1 2 3 10 5 16 8 4 4 5 6 3 7 22 11 34 17 52 26 13 40 20 10 8 9 28 14 7 10 11 12 6 13 14 15 46 23 70 35 106 53 160 80 40 16 17 18 9 19 58 29 88 44 22 20 21 64 32 16 22 23 24 12 the result of my code: 1 4 4 2 2 1 3 10 10 5 4 2 5 16 6 3 3 10 7 22 22 11 8 4 4 2 9 28 28 14 14 7 10 5 11 34 12 6 6 3 13 40 40 20 20 10 14 7 15 46 46 23 23 70 16 8 17 52 52 26 26 13 13 40 18 9 9 28 19 58 58 29 29 88 88 44 44 22 22 11 what should i change in the code, so we have matching outputs. thanks in advance
the creation of each series will stop when a value greater than a thousand or a value that has already appeared in a previous series is produced. Up to 24, none of the produced values is greater than a thousand, but the posted code still has an access out of bounds bug: int main() { int array[25]; // ^^ for (int i = 1; i < 25; i++) { int currentNum = i; int theNumAfter; // ... array[currentNum] = currentNum; // ... array[theNumAfter] = theNumAfter; // ... } // ... } Note the many of numbers in the expected output are greater than 25. I'm not sure what this part was supposed to achive: for (int i = 0; i <= 25; i++) { // ^^^^^^^ it "checks" only the first 25 values that may occur if (array[i] == currentNum) { occured = true; cout << endl; // <-- The duplicate should be printed before the newline. // Here it should break out of the loop. } } array[currentNum] = currentNum; cout << currentNum << " "; But it fails to produce the expected output. I'd use a simple array of 1000 bools to memorize the already occurred numbers. #include <iostream> int main() { constexpr int limit{ 1'000 }; bool already_seen[limit + 1]{}; for (int i = 1; i < 25; i++) { int current{ i }; while ( current <= limit and not already_seen[current] ) { std::cout << current << ' '; already_seen[current] = true; if ( current % 2 == 0) { current /= 2; } else { current = (3 * current) + 1; } } std::cout << current << '\n'; } } Testable here.
How to create an algorithm to find all possible pairings (referring to the chinese postman problem)?
When trying to solve the chinese postman problem you will have to find minimum cost of all possible pairings of all odd vertexes in the graph and add found edges (pairings), which my question is almost about. How to implement an algorithm, which returns all possible pairings? or how to fix mine. I got a starting point, but am not able to go or think further. I tried looking on following topics but they did'nt help me unfortunetly. How should I generate the partitions / pairs for the Chinese Postman problem? or Find the pairings such that the sum of the weights is minimized? std::vector<std::vector<int>> Postman::pairOdd(std::vector<int> vertices) { std::vector<std::vector<int>> pairs; if (vertices.empty()) { return std::vector<std::vector<int>>(); } else { auto it = std::min_element(vertices.begin(), vertices.end()); int i = *it; vertices.erase(it); for (int index = 0; index < vertices.size(); index++) { int j = vertices[index]; vertices.erase(vertices.begin() + index); pairs.push_back(std::vector<int>{i, j}); std::vector<std::vector<int>> returnValue = pairOdd(vertices); pairs.insert(pairs.end(), returnValue.begin(), returnValue.end()); vertices.insert(vertices.begin(), j); } vertices.insert(vertices.begin(), i); } return pairs; } Output with std::vector<std::vector<int>> res = pairOdd(std::vector<int>{1,2,3,4,5,6}); for (auto v : res) { for (auto u : v) { std::cout << u; } std::cout << std::endl; } should be: 1 2 3 4 5 6 1 2 3 5 4 6 1 2 3 6 4 5 1 3 2 4 5 6 1 3 2 5 4 6 1 3 2 6 4 5 1 4 2 3 5 6 1 4 2 5 3 6 1 4 2 6 3 5 1 5 2 3 4 6 1 5 2 4 3 6 1 5 2 6 3 4 1 6 2 3 4 5 1 6 2 4 3 5 1 6 2 5 3 4 But is: 12 34 56 35 46 36 45 13 24 56 25 46 26 45 14 23 56 25 36 26 35 15 24 36 23 46 26 34 16 25 34 24 35 23 45 I can't quite fix how I insert into the vector. When looking at the output, you can see that it is almost right (ignoring the formatting). First line 12 34 45 is correct. Second 35 46, when it has to be 12 35 36, seems that only the first pair is missing, which you will notice applies to every pairings. Update: So I came up with another algorithm which seems to be promising, but instead of missing some pairs, I get duplicates. A solution is highly appreciated. If I find one myself I will post it. std::vector<std::vector<int>> Postman::aaa(std::vector<int> vertices, std::vector<int> list, int in1, int in2) { std::vector<std::vector<int>> pairs; if (vertices.empty()) { list.push_back(in1); list.push_back(in2); pairs.push_back(list); return pairs; } else { auto it = std::min_element(vertices.begin(), vertices.end()); int i = *it; vertices.erase(it); for (int index = 0; index < vertices.size(); index++) { int j = vertices[index]; vertices.erase(vertices.begin() + index); if (in1 != 0 && in2 != 0) { list.push_back(in1); list.push_back(in2); } std::vector<std::vector<int>> returnValue = aaa(vertices, list, i, j); pairs.insert(pairs.end(), returnValue.begin(), returnValue.end()); vertices.insert(vertices.begin(), j); } vertices.insert(vertices.begin(), i); } return pairs; } Output: 123456 12123546 1212123645 132456 13132546 1313132645 142356 14142536 1414142635 152436 15152346 1515152634 162534 16162435 1616162345
So I found a solution for the second algorithm I mentioned. The problem was I send the pair to the next recursion step to be then added in this step. So when you returned from a recursion step the pairing would still be in there. So I just deleted this pair, so the new one can be added. Instead of just returning an int vector I made an pair vector. Visualizing the return value better. I am willing to listen to any improvements to this algorithm or any good practices. I am willing to listen to any improvements to this algorithm or any good practises. std::vector<std::vector<std::pair<int, int>>> Postman::pairing(std::vector<int> vertices, std::vector<std::pair<int, int>> list) { std::vector<std::vector<std::pair<int, int>>> pairs; if (vertices.empty()) { pairs.push_back(list); return pairs; } else { auto it = std::min_element(vertices.begin(), vertices.end()); int i = *it; vertices.erase(it); for (int index = 0; index < vertices.size(); index++) { int j = vertices[index]; vertices.erase(vertices.begin() + index); std::pair<int, int> pair(i, j); list.push_back(pair); std::vector<std::vector<std::pair<int, int>>> r = pairing(vertices, list); list.erase(list.end() - 1); pairs.insert(pairs.end(), r.begin(), r.end()); vertices.insert(vertices.begin(), j); } } return pairs; } std::vector<std::vector<std::pair<int, int>>> a = pairing(vertices, std::vector<std::pair<int, int>>()); for (auto v : a) { for (auto p : v) { std::cout << '(' << p.first << ' ' << p.second << ')'; } std::cout << std::endl; }
g++ optimization breakes for loop
So, I have this codesnippet here for (int t = WILSON_TEMPORAL_START, t_i = 0; t <= WILSON_TEMPORAL_END; t++, t_i++) { for (int r = WILSON_SPATIAL_START, r_i = 0; r <= WILSON_SPATIAL_END; r++, r_i++) { std::cout << r << " " << WILSON_SPATIAL_END << std::endl; wilson_loop[conf_id][t_i][r_i] = compute_wilson_loop(t, r, iu1, iu2); } } I run my g++ compiler in two different optimization versions -O1 and -O2, but the terminal output is differently. With -O1 2 12 3 12 4 12 5 12 6 12 7 12 8 12 9 12 10 12 11 12 12 12 2 12 3 12 4 12 ... With -O2 2 12 3 12 4 12 5 12 6 12 7 12 8 12 9 12 10 12 11 12 12 12 13 12 14 12 15 12 ... The code works fine if I change the inner loop to: for (int t = WILSON_TEMPORAL_START, t_i = 0; t <= WILSON_TEMPORAL_END; t++, t_i++) { for (int r = WILSON_SPATIAL_START, r_i = 0; r <= WILSON_SPATIAL_END; r++, r_i++) { std::cout << r << " " << WILSON_SPATIAL_END << std::endl; // wilson_loop[conf_id][t_i][r_i] = compute_wilson_loop(t, r, iu1, iu2); } } Some useful definitions are: static double compute_wilson_loop(int time_extend, int space_extend, SUN_mat iu1[VOL][DIM], SUN_mat iu2[VOL][DIM]) void wilson::measure_wilson_loop(SUN_mat pu[VOL][DIM], double wilson_loop[CLEN][TLEN][SLEN], int conf_id) { ... } I know, that I can find a workaround here, but I really want to understand, why this happens.
I just solved the problem, I made an error in defining the preprocessor constants. I'm still not sure, why it changes output when using a different optimization mode, but it works now :)
Splitting std::vector of size m into vector of vectors of size n
Given a vector [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17], what are some possible approaches to construct [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17]], focusing primarily on readability? At the moment, I have correctly defined the starting and ending indexes of all the subarrays, and was trying to use std::copy(cam.begin() + start, cam.begin() + end+ 1, vec.begin()); to construct a new vector.. resulting in: terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc
If you're just after some code that can split a vector into a vector of up-to-five-element vectors, this should do it. It's bigger than necessary only because of the test harness around it. The "meat" of the code is the templated function makeVecOfVecs(), and the single-line call to it. It's quite handy to do this sort of thing as a template since it then becomes easy to extend to other data types. The code is: #include <iostream> #include <vector> // From a flat vector, construct a vector of sub-vectors, each of a // specific size (except the last sub-vector, which may be smaller). template<class T> std::vector<std::vector<T>> makeVecOfVecs( const std::vector<T> &in, unsigned int sz ) { std::vector<std::vector<T>> out; for (int i = 0; i < in.size(); i += sz) { if (in.size() - i < sz) sz = in.size() - i; std::vector<T> newVec(sz); std::copy(in.begin() + i, in.begin() + i + sz, newVec.begin()); out.push_back(newVec); // As pointed out in a comment, you could probably // replace the three preceding lines with just: // out.emplace_back(in.begin() + i, in.begin() + i + sz); // and avoid creating newVec. } return out; } // Test harness for the above function. int main(int argc, char *argv[]) { // Default to 17 values, allow for override. Could probably // make more robust, but is IS only test code. int count = 17; if (argc > 1) count = atoi(argv[1]); // Input data for testing, print for validation. std::vector<int> in; for (int i = 0; i < count; ++i) in.push_back(i + 1); std::cout << "\nInput (" << count << "):"; for (const auto &inElem: in) std::cout << " " << inElem; std::cout << "\n"; auto out = makeVecOfVecs<int>(in, 5); // Output of result for validation. std::cout << "Output:\n"; for (const auto &outElem1: out) { std::cout << " "; for (const auto &outElem2: outElem1) std::cout << " " << outElem2; std::cout << "\n"; } } A few sample runs are shown below for validation (you'll see I've asked for a chunk size of 10 rather than 5, that's just to use less space in the answer): pax:~> for i in "" 22 20 0 -9 1; do ./testprog ${i}; done Input (17): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 Output: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 Input (22): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 Output: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 Input (20): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Output: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Input (0): Output: Input (-9): Output: Input (1): 1 Output: 1
If the vector of vectors is interpreted as a matrix, the first n-1 rows can be filled in a straightforward way by copying segments from the one-dimensional input vector. Only the last row of that "matrix" requires some attention, as it may not be completely filled. #include <iostream> #include <algorithm> #include <vector> #include <numeric> #include <cmath> int main() { // create initial data int vecSize = 17; std::vector<int> inVec(vecSize); std::iota(inVec.begin(), inVec.end(), 1); // prepare new container int ncol = 5; int nrow = std::ceil(float(vecSize) / float(ncol)); std::vector<std::vector<int>> outVecVec(nrow); // row-wise copy for (int i = 0; i < nrow; ++i) { int rowLength = ncol; if (i == nrow - 1 && vecSize % ncol != 0) { rowLength = vecSize % ncol; // length of last row, if not filled } outVecVec[i].resize(rowLength); auto vecIndex = inVec.begin() + i * ncol; std::copy(vecIndex, vecIndex + rowLength, outVecVec[i].begin()); } // print output for (int i = 0; i < nrow; ++i) { for (int j = 0; j < outVecVec[i].size(); ++j) std::cout << outVecVec[i][j] << " "; std::cout << std::endl; } } demo: https://godbolt.org/z/w9aDrE
Using the range-v3 library this becomes very simple, and readable: std::vector<int> v = ... int m = ... auto vs = v | ranges::views::chunk(m) | ranges::to<std::vector<std::vector<int>>>; Here's a demo.
Assigning a vector to a matrix column in Eigen
This question was asked in haste. The error in my original program, was not the typo in the code that is displayed here. The error was that in my program v was not getting populated due to some conditions. The more useful takeaway from this thread is the demonstration of copying a std::vector to all rows or columns of an Eigen Matrix, in the accepted answer. I want to copy vectors into the columns of a matrix, like the following: #include <Eigen/Dense> #include <vector> #include <iostream> int main() { int m = 10; std::vector<Eigen::VectorXd> v(m); Eigen::MatrixXd S(m,m); for (int i = 0; i != m; ++i) { v[i].resize(m); for (int j = 0; j != m; ++j) { v[i](j) = rand() % m; } //S.cols(i) = v[i]; //needed something like this } return 0; } S is of type Eigen::MatrixXd and dimension mxm. v is a std::vector of Eigen::VectorXd, where each Eigen::VectorXd is of size m and there are m of them in v.
Regarding the original question, you need to wrap the std::vector with an Eigen::Map. You could/should also make the operation a one-liner. The reworded question is reduced to a typo. S.cols(i) should be S.col(i). int main() { size_t sz = 6; Eigen::MatrixXd S(sz, sz); std::vector<double> v(sz); std::vector<Eigen::VectorXd> vv(sz); for(int i = 0; i < sz; i++) { v[i] = i*2; vv[i] = Eigen::VectorXd::LinSpaced(sz, (i+sz), (i+sz)*2); } for (int i = 0; i != sz; ++i) S.col(i) = vv[i]; std::cout << S << "\n\n"; S.rowwise() = Eigen::Map<Eigen::RowVectorXd>(v.data(), sz); std::cout << S << "\n\n"; S.colwise() = Eigen::Map<Eigen::VectorXd>(v.data(), sz); std::cout << S << "\n\n"; return 0; } which would output 6 7 8 9 10 11 7.2 8.4 9.6 10.8 12 13.2 8.4 9.8 11.2 12.6 14 15.4 9.6 11.2 12.8 14.4 16 17.6 10.8 12.6 14.4 16.2 18 19.8 12 14 16 18 20 22 0 2 4 6 8 10 0 2 4 6 8 10 0 2 4 6 8 10 0 2 4 6 8 10 0 2 4 6 8 10 0 2 4 6 8 10 0 0 0 0 0 0 2 2 2 2 2 2 4 4 4 4 4 4 6 6 6 6 6 6 8 8 8 8 8 8 10 10 10 10 10 10