使用用户定义的类创建一个向量,并在实例化‘ struct std :: _ vector_base ....没有命名‘ value_type’在MyClass类中’
我正在创建一个简单的类
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class MyClass {
int p;
public:
MyClass( int q ) { p = q; }
};
,但是当我尝试创建此矢量时,
vector<int, MyClass> vec1(1);
我的代码断开并引发了此例外,
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;
我可以解决此手段,我可以将int类型与用户定义的vector中的用户类型一起使用,例如this vector&lt; int,myclass&gt;
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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
向量
有两个模板参数。您正在尝试创建一个使用
myClass
作为分配器的向量。但是,myClass
不提供vector
期望的呼叫,因此它无法编译。您想完成什么?
如果您想要一个包含
myClass
对象的向量,则应声明vector&lt; myClass&gt;
。如果您想要一个包含对象对的向量,一个int和myClass
,则可以使用vector&lt; pair&lt; int,myclass&gt;
(如其他注释者所述) 。但是,从您的问题中尚不清楚您真正想要什么。
vector
has two template parameters.You are trying to create a vector that uses
MyClass
as the allocator. However,MyClass
does not provide the calls that thevector
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 avector<MyClass>
. If you want a vector that contains pairs of objects, an int and aMyClass
then you can usevector<pair<int, MyClass>
(as the other commenters have mentioned).But it is not clear from your question what you really want.
我在向量中使用PAIR ,
如果 在线gdb.com/d5gtqjijt“ rel =“ nofollow noreferrer”>工作演示
You can iterate through the pair elements of the vector and print the data member
p
as shown below:Working demo