Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast vector<int> to int*

Tags:

c++

I have to maintain a program that nobody has touched since 2004.

class CSolver
{  
 ...  
 ClauseIdx add_clause (int * lits, int n_lits);
}

void and2 (CSolver & solver)   
{  
vector <int> lits;  
...  
solver.add_clause(lits.begin(), lits.size());  
}

The compiler complains that:

error: no matching function for call to ‘CSolver::add_clause(__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, size_t)’

I try to cast it

solver.add_clause((int*)lits.begin(), lits.size());

But there is still a complaint:

error: invalid cast from type ‘__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >’ to type ‘int*’

I want to look for a quick fix on this, because changing interface of CSolver will result changing the whole program.

Thanks in advance.

like image 501
sean Avatar asked Nov 29 '22 08:11

sean


2 Answers

If you can compile against c++11, you can use

solver.add_clause(lits.data(), lits.size());

http://en.cppreference.com/w/cpp/container/vector/data

like image 43
tomahh Avatar answered Dec 10 '22 12:12

tomahh


Like this:

solver.add_clause(lits.data(), lits.size());

Don't add casts without understanding what you're doing.

The function wants an array of ints, and it's asking for them by a pointer to the first element along with a size. This is a common C convention.

Lucky for us, std::vector stores elements precisely as a contiguous array, so we can get a pointer to the first element (lits.data(), &lits[0], &lits.front(), etc.) and then just pass the size.

like image 176
GManNickG Avatar answered Dec 10 '22 10:12

GManNickG