【问题标题】:Initializing vector with data not working - push_back() does work使用数据初始化向量不起作用 - push_back() 确实有效
【发布时间】:2020-04-17 15:29:33
【问题描述】:

我正在尝试创建一个 typedef 向量。每当我尝试使用这些 typedef 之一初始化向量时,它都会给出 no instance of constructor 错误。

typedef定义如下:

typedef palam::geometry::Pt2<uint16_t> CPoints;

我正在尝试像这样初始化一个向量:

CPoints point1(10, 15);
CPoints point2(15, 20);
std::vector<CPoints> points(point1, point2);

但这不起作用。我可以通过使用NULL 值初始化向量然后使用push_back() 函数来解决这个问题,就像这样

CPoints point1(10, 15);
CPoints point2(15, 20);
std::vector<CPoints> points(NULL);
points.push_back(point1);
points.push_back(point2);

这项工作似乎有点混乱,我相信一定有更好的方法来解决这个问题。有谁知道为什么我无法使用 typedefs 直接初始化向量?

【问题讨论】:

  • std::vector&lt;CPoints&gt; points(point1, point2); 这和你想的不一样。查看文档。
  • std::vector&lt;CPoints&gt; points(NULL); -- 鉴于NULL 为0,NULL 绝对什么都不做。只需声明 vector 就足够了。
  • @PaulMcKenzie 将参数完全留空会导致 push_back() 函数不起作用。它给出了一个expression must have a class type 错误。
  • @BrentMB 所以你这样做了:std::vector&lt;CPoints&gt; points();?好吧,您已经发现了“最令人头疼的解析”问题。这是一个名为 points 的函数的声明,它不接受任何参数,并返回一个 std::vector&lt;CPoints&gt;
  • @PaulMcKenzie 有趣的是,我以前从未听说过这种歧义。我会调查的!

标签: c++ vector initialization initializer-list


【解决方案1】:

这个sn-p:

std::vector<CPoints> points(point1, point2);

调用 vector constructor 接受 2 个参数。如果你想用多个元素初始化一个vector,使用{},像这样:

std::vector<CPoints> points {point1, point2};

这调用了重载号 9,它接受一个初始化列表。

【讨论】:

  • 谢谢。这完美地回答了我的问题。
  • @BrentMB 如果这回答了您的问题,请考虑接受它。
【解决方案2】:

使用这条记录

std::vector<CPoints> points = { point1, point2 };

或者这个

std::vector<CPoints> points { point1, point2 };

或者这个

std::vector<CPoints> points( { point1, point2 } );

如果您想同时向一个向量提供多个对象,则使用初始化列表。

否则编译器会尝试应用这些构造函数之一

vector(size_type n, const T& value, const Allocator& = Allocator());
template <class InputIterator>
vector(InputIterator first, InputIterator last,
const Allocator& = Allocator());

对于声明中的指定参数无效

std::vector<CPoints> points(point1, point2);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-10
    • 2014-10-28
    • 2020-05-16
    • 2020-01-05
    • 2015-10-21
    • 1970-01-01
    相关资源
    最近更新 更多