Hi, Trying to learn STL.
I tried implementing the dynamic array with the STL.
I wrote the following code and tried with int array works fine, but when i try with string array input, i get the error..can you please help me,
#include <iostream>
#include <vector>
using namespace std;
template < typename T>
class dyn_arr{
public:
//Dedault constructor
dyn_arr() {};
//Constructor
dyn_arr( int rows, int cols)
{
arr.resize(rows);
for(int i=0; i<rows; i++)
{
vector<int> row;
for(int j=0; j<cols; j++)
{
row.resize( cols);
fill(row.begin(), row.end(), "hello");
}
arr.push_back(row);
}
}
void print_array(int rows, int cols)
{
for(int i=0; i<cols; i++)
{
for(int j=0; j<rows; j++)
cout << arr[i][j] << "\t";
cout << endl;
}
}
private:
vector< vector< T > > arr;
};
int main() {
int rows=2, cols=2;
dyn_arr<int> loc_arr(rows,cols);
loc_arr.print_array(rows, cols);
}
For string: main looks like this
int main() {
int rows=2, cols=2;
dyn_arr<string> loc_arr(rows,cols);
loc_arr.print_array(rows, cols);
}
Error:
dyn_arr.cpp: In constructor `dyn_arr<T>::dyn_arr(int, int) [with T =
std::string]':
dyn_arr.cpp:58: instantiated from here
dyn_arr.cpp:32: error: no matching function for call to `
std::vector<std::vector<std::string, std::allocator<std::string> >,
std::allocator<std::vector<std::string, std::allocator<std::string> > > >::
push_back(std::vector<int, std::allocator<int> >&)'
/usr/include/c++/3.3.1/bits/stl_vector.h:596: error: candidates are: void
std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp =
std::vector<std::string, std::allocator<std::string> >, _Alloc =
std::allocator<std::vector<std::string, std::allocator<std::string> > >]
/usr/include/c++/3.3.1/bits/stl_algobase.h: In function `void
std::fill(_ForwardIter, _ForwardIter, const _Tp&) [with _ForwardIter =
__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >,
_Tp = char[6]]':
dyn_arr.cpp:30: instantiated from `dyn_arr<T>::dyn_arr(int, int) [with T = std::string]'
dyn_arr.cpp:58: instantiated from here
/usr/include/c++/3.3.1/bits/stl_algobase.h:517: error: invalid conversion from
`const char*' to `int'