I am creating a simple class
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class MyClass {
int p;
public:
MyClass( int q ) { p = q; }
};
but when I try to create this vector
vector<int, MyClass> vec1(1);
my code breaks and throws this exception
vector<int,MyClass> vec1(1);
In instantiation of ‘struct std::_Vector_base<int, MyClass>’:
/usr/include/c /9/bits/stl_vector.h:386:11: required from ‘class std::vector<int, MyClass>’
vector_class.cpp:19:26: required from here
/usr/include/c /9/bits/stl_vector.h:84:21: error: no type named ‘value_type’ in ‘class MyClass’
84 | rebind<_Tp>::other _Tp_alloc_type;
Can I resolve this means can I use int type with user defined types in vector like this vector<int,MyClass>
CodePudding user response:
vector
has two template parameters.
- The first is the type of elements to be stored into the vector.
- The second is an allocator, a helper class that allocates and frees memory used by the vector.
You are trying to create a vector that uses MyClass
as the allocator. However, MyClass
does not provide the calls that the vector
expects, so it fails to compile.
What are you trying to accomplish?
If you want a vector containing objects of MyClass
, then you should declare a vector<MyClass>
. If you want a vector that contains pairs of objects, an int and a MyClass
then you can use vector<pair<int, MyClass>
(as the other commenters have mentioned).
But it is not clear from your question what you really want.
CodePudding user response:
how to print p if I am using pair in vector as u shown
You can iterate through the pair elements of the vector and print the data member p
as shown below:
class MyClass {
public:
int p;
public:
MyClass( int q ):p(q)
{
}
};
int main()
{
std::vector<std::pair<int, MyClass>> vec1{{1, MyClass(44)}, {2,MyClass(45)}, {3,MyClass(46)}};
//iterate through the vector and print data member p
for(const auto&myPair: vec1)
{
//-----------------vvvvvvvvvvvvvv-------------->print the data member p
std::cout<<myPair.second.p<<std::endl;
}
}