2d vectors, seg fault
Sep 23, 2016 at 6:51am UTC
I have this function that is supposed to take a 2d vector by reference and rotates it clockwise by 90 degrees. For some files I get a seg fault and for some the result is not correct.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
void pgm_cw( vector <IVec> &p )
{
vector <IVec> temp; // temporary vector of vectors of ints
int count = 0; // count variable
int count2 = 0; // 2nd count variable
temp.resize( p.size() );
for ( count = 0; count < p.size(); count++ )
{
temp[count].resize( p[count].size() );
for ( count2 = count; count2 < temp[count].size(); count2++ )
{
temp[count][count2] = p[count2][count];
}
}
for ( count = 0; count < temp.size(); count++ )
{
for ( count2 = 0; count2 < temp[count].size(); count2++ )
{
temp[count][count2] = temp[count][p[count].size()-count2-1]; // set temp vector to p with 90 degree rotation
}
}
p = temp; // set p equal to temp
}
Can someone help me figure out whats wrong
Sep 23, 2016 at 7:04am UTC
temp[count][count2] = p[count2][count];
This doesn't look right. I think it should be
temp[count][count2] = p[count ][count2 ];
Sep 23, 2016 at 8:07am UTC
I got it. thanks for the help
Last edited on Sep 24, 2016 at 3:09am UTC
Sep 23, 2016 at 11:28pm UTC
If the height and width of the original matrix are not equal, the height and width of the transposed matrix will not be equal to those of the original matrix.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
#include <iomanip>
#include <iostream>
#include <vector>
using ivec = std::vector<int >;
using matrix = std::vector<ivec>;
matrix transpose(const matrix& m) {
const auto m_rows = m.size();
const auto m_cols = m.front().size();
matrix result(m_cols, ivec(m_rows));
for (std::size_t i = 0; i < m_rows; ++i)
for (std::size_t j = 0; j < m_cols; ++j)
result[j][i] = m[i][j];
return result;
}
std::ostream& operator <<(std::ostream& os, const matrix& m) {
for (std::size_t i = 0; i < m.size(); ++i) {
for (std::size_t j = 0; j < m[i].size(); ++j)
os << std::setw(5) << m[i][j];
os << '\n' ;
}
return os;
}
int main() {
matrix m = {
{ 1, 2, 3 },
{ 4, 5, 6 }
};
std::cout << m << '\n' ;
std::cout << transpose(m) << '\n' ;
}
Topic archived. No new replies allowed.