Bremsstrahlung
Bremsstrahlung

Reputation: 63

C++ Element access is failing to work?

this is a super simple question but I cannot seem to see what has gone wrong. What this code does is it counts the number of elements in the pixID vector and returns that sum to a diagonal element in the square matrix PtP. However even though 'i' in the first loop reads: 0,5,10,15 for the elements the output looks like this:

1,0,0,0,
0,0,3,0,
0,0,0,0,
0,3,0,0,

instead of the desired:

1,0,0,0,
0,3,0,0,
0,0,2,0,
0,0,0,2,

Any idea what is going on here?

  double where(std::vector<double> &vec,unsigned int &v){

     double count = 0;
     int val;
     for(std::vector<double>::iterator it = vec.begin();
         it != vec.end();
         ++it){
       if(*it == val){
         count++;
       }
     }

  return count;
  }


  int main(){

  unsigned int pixSide = 2;
  int id;
  std::vector<double> pixID {1,1,2,3,0,2,1,3};
  std::vector<double> PtP (pixSide*pixSide);

  for(unsigned int i=0;i<pixSide*pixSide;i++){
    id = i*pixSide*pixSide + i;
    std::cout << id << std::endl;
    PtP[id] = where(pixID,i);
  }

  for(int i=0;i<pixSide*pixSide;i++){
    for(int j=0;j<pixSide*pixSide;j++){
      std::cout << int(PtP[i*pixSide + j]) << ',';
      if(j==pixSide*pixSide-1){
    std::cout << std::endl;
      }
    }
  }
}

Upvotes: 0

Views: 83

Answers (1)

svk
svk

Reputation: 5919

First, you're not using the parameter "v" in where(). Instead, you're using the uninitialized local variable "val".

Second, I think you may be confusing the dimensions of your objects at a few points. I think you're getting confused about whether you're keeping just the diagonal or the whole matrix.

This way you will consistently be keeping the whole matrix:

std::vector<double> PtP (pixSide*pixSide);

should be

std::vector<double> PtP (pixSide*pixSide*pixSide*pixSide);

and

std::cout << int(PtP[i*pixSide + j]) << ',';

should be

std::cout << int(PtP[i*pixSide*pixSide + j]) << ',';

Of course, this is wasteful for such a sparse matrix -- I don't know whether that matters in your application (are your real numbers larger than pixSide=2?).

Upvotes: 1

Related Questions