C++,对象 vector

标签 c++ oop vector

在 C++ 中,使用对象 vector 是个好主意吗?如果不是,这段 C++ 代码有什么问题?

#include <vector>

using namespace std;

class A {};

int main() {

        vector<A*> v ( new A);
        return 0;
}

来自 g++:

13: error: invalid conversion from A*' tounsigned int'

最佳答案

constructor for std::vector采用初始长度,而不是元素。

这意味着您通常会这样做:

vector<A*> v(1); // Initialize to length 1
v.push_back( new A() ); // Add your element...

您收到编译器错误是因为在您的系统上,size_type 被定义为 unsigned int。它试图使用该构造函数,但失败了,因为您向它传递了一个指向 A 的指针。

关于C++,对象 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2411704/

相关文章:

c++ - QT:文件存储在 appdata 下名为 VirtualStore 的文件夹中

c++ - 折叠表达式和空参数包 : what's the expected result?

JavaFX 将抽象类对象添加到 arraylist

matlab - 没有足够的输入参数继承Matlab

string - [] 字符串运算符,与向量切片链接

python - 在 Cython 中使用 C+ +'s ` str.erase()`

用于 string_view 的 C++17 运算符?

java - Java中的Iterator接口(interface)有什么好处?

C++ : Pop_back a paired vector

R:向量列表 - 将相同的向量分组在一起