error: cannot convert ‘int*’ to ‘std::vector<int, std::allocator<int> >*’ in initialization

I wrote a function to read all the elements in order from a binary search tree and then put them inside a vector, however I get an error at the line where I declare my new vector and I'm not sure what's wrong.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    void _to_vector(bst_node* ptr, std::vector<T>* V, int& index){
      if (ptr == nullptr)
        return;
      else{
        _to_vector(ptr->left, V, index);
        V[index++] = ptr->val;
        _to_vector(ptr->right, V, index);
      }
    }
    
    std::vector<T>* to_vector() {
      std::vector<T>* V = new T;
      int index = 0;
      _to_vector(root,V,index);
      return V;
    }


You probably meant (*V)[index++].

Note:
1
2
3
4
5
6
7
8
std::vector<int> v;
int i = 0;
v[i++] = 0; // <-- this
v[i++] = 0; // <-- and this is not how you grow a vector

//this is:
v.push_back(0); 
v.push_back(0);
You are right, I forgot about that, I've changed my function to look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    void _to_vector(bst_node* ptr, std::vector<T>* V){
      if (ptr == nullptr)
        return;
      else{
        _to_vector(ptr->left, V);
        V->push_back(ptr->val);
        _to_vector(ptr->right, V);
      }
    }

    std::vector<T>* to_vector() {
      std::vector<T>* V = new T;
      _to_vector(root,V);
      return V;
    }


However, I'm still getting the same error at the line where the vector is declared (12), which is weird... this is where the function gets called:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int test(int h, int n) {
  // BST *t = build_balanced(h);
  //
  bst<int> *t = build_balanced(h);

  int success = 1;
  int i;

  std::vector<int> *a = t->to_vector();

  if(a->size() == n) {
    for(i=0; i<n; i++) {
      if((*a)[i] != i+1)
        success = 0;
    }
  }
  else
    success = 0;
  delete t;
  delete a;
  return success;
}
Last edited on
For anyone still wondering I found the error to be the fact that I declared my pointer as a new T, instead of as a new vector<T>

1
2
std::vector<T>* V = new T; // <-- bad
std::vector<T>* V = new vector<T>; // <-- good 
Topic archived. No new replies allowed.