Reputation: 57
I'm trying to implement a container class using the code given in the Chapter 18 of 'Programming Principles and Practices using C++'. And when I write the code for the initialization using initializer_list I get this error: 'conversion from '::size_t' to 'int' requires a narrowing conversion'.
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
class vector
{
public:
vector(int s)
:sz{ s },
elem{ new double[sz] }
{
for (int i = 0; i < sz; i++)
elem[i] = 0.0;
}
vector(std::initializer_list<double>lst)
:sz{ lst.size() }, elem{ new double[sz] }
{ //compiler points to here for the error
std::copy(lst.begin(), lst.end(), elem);
}
~vector() { delete[] elem; }
int size() const { return sz; }
double get(int n) const { return elem[n]; }
void set(int n, double d) { elem[n] = d; }
private:
int sz;
double* elem;
};
Upvotes: 3
Views: 7486
Reputation: 7111
You're trying to convert a size_t
into an int
. Assuming 32-bits, size_t
can hold up to 2^32 because it's unsigned, whereas int
can only hold 2^31 (because it can have negative values also).
When you do this:
vector(std::initializer_list<double>lst)
:sz{ lst.size() }
If lst.size()
is greater than the value stored by an int
, then the value can't properly be stored. The solution would be to just use std::vector
internally, and get rid of the sz
member, but seeing as though it looks as if you're trying to make your own vector
class, you should just make sz
a size_t
, since it better represents what you're trying to do. After all, it's not as if your vector
can have < 0
elements in it.
Upvotes: 5