richiE
richiE

Reputation: 33

Im trying to put elements into a multidimensional array

I'm doing a task on codewars and I'm almost done but i get an error with my answer vector.

1

What I want to do here is to put the value of i and sum into a multidimensional array (an array of arrays)

if (sum == x*x  ){
          
          answer.push_back(i, sum);
            
        }

But it just throws out an error that somethings wrong with this line of code

main.cpp:26:17: error: member reference base type 'std::vector<int> [n][2]' is not a structure or union
          answer.push_back(i, sum);
          ~~~~~~^~~~~~~~~~
main.cpp:31:14: error: no viable conversion from returned value of type 'std::vector<int> [n][2]' to function return type 'std::vector<std::pair<long long, long long> >'
      return answer;

I don't have a lot knowledge about static functions and vectors in general so maybe you guys can enlighten me on how to do it correctly?

Here the full code of my function:

static std::vector<std::pair<long long, long long>> listSquared(long long m, long long n) {
      int x, sum = 0;
      std::vector< int > answer[n][2];
      
      
      for(int i=m; i<n ; i++) {
        for(int j=1; j<i; j++) {
          if(i % j == 0) {
            sum=sum+j*j;
          }
        }
        if (sum == x*x  ){
          
          answer.push_back(i, sum);
            
        }
        sum = 0;
      }
      return answer;
    };
};

Upvotes: 0

Views: 63

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

  1. Type of result array (vector) and return type should be matched.
  2. You declared an array of vector, but you will need only one array.
  3. std::vector don't have push_back that take 2 arguments. You should make pairs to put.
  4. You don't need ; after function definition.
  5. There is an extra }; after the function definition.
  6. Value of x is used without being uninitialized.

Try this:

static std::vector<std::pair<long long, long long>> listSquared(long long m, long long n) {
      int x = 0, sum = 0;
      std::vector< std::pair<long long, long long> > answer;
      
      
      for(int i=m; i<n ; i++) {
        for(int j=1; j<i; j++) {
          if(i % j == 0) {
            sum=sum+j*j;
          }
        }
        if (sum == x*x  ){
          
          answer.push_back(std::make_pair(i, sum));
            
        }
        sum = 0;
      }
      return answer;
}

Upvotes: 1

Related Questions