【问题标题】:Can't use vector::insert "no instance of overloaded function..."不能使用vector::insert“没有重载函数的实例......”
【发布时间】:2017-04-16 13:04:45
【问题描述】:
class largeNum
{

public:
     std::vector<int>& getValue();

private:
    std::vector<int> value;
};

这是我使用 getValue() 方法的基类。

std::vector<int>& largeNum::getValue() {
    return value;
}

现在尝试在向量中插入值时出现错误:

largeNum operator+(largeNum& summand1, largeNum& summand2) {
    largeNum returnNum;
    int size = 0;
    //adapts the smaller vektor to the larger vektor by resizing him and reversing him so 1 turns into 00...01
    if (summand1.getValue().size() > summand2.getValue().size()) {
        for (int i = 0; i < (summand1.getValue().size() - summand2.getValue().size()); i++) {
            //error happens here
            summand2.getValue().insert(0, 0);
        }
    }
[...]

有趣的是,我可以使用除vector::insertvector::erase 之外的所有方法。

它给了我一个错误,说我需要传递两个整数,我正在这样做。

没有重载函数“std::vector<_ty _alloc>::insert [with _Ty=int, _Alloc=std::allocator]”的实例与参数列表匹配

【问题讨论】:

标签: c++ algorithm c++11 vector compiler-errors


【解决方案1】:

没有一个overloads of vector&lt;T&gt;::insert 占据位置。它们都带有一个迭代器,因此您需要在向量上调用begin 以获取插入位置。

为避免两次调用summand1.getValue(),请将结果存储在引用中:

std::vector<int> &tmp = summand1.getValue();
tmp.insert(tmp.begin(), 0);

【讨论】:

  • 加一个,虽然我很遗憾看到你是一个右对齐的星号/&符号的人;( sniff
  • @BoundaryImposition C/C++ 语法的一个不幸特性,它允许我们在一个声明中声明许多不同类型的对象(例如int x, *y, **z),这迫使我进入了右对齐者的阵营。我希望 C++ 设计人员在新语言的早期就对它做点什么,但现在做任何事情都为时已晚。
  • 面对这么多更重要的考虑,我仍然不明白为什么右对齐者会坚持这种极端情况(在我们甚至不应该使用的句法特性中) !
  • 加 1 用于右对齐 &/* :) 实用且个性化,更美观。
  • @user54264611634646244:现成的回应:) kera.name/articles/2010/05/…
【解决方案2】:

insert() 的第一个参数必须是迭代器,而不是 int

此外,让公共成员函数返回对私有成员的引用是一种不好的气味,因为您实际上是在破坏封装。

因此我的建议是使用“告诉,不要问”的模式:

class largeNum
{

public:
     void insertFront(int value);  // implemented via value.insert() and value.begin()

private:
    std::vector<int> value;
};

【讨论】:

    猜你喜欢
    • 2019-08-11
    • 1970-01-01
    • 2016-03-16
    • 1970-01-01
    • 1970-01-01
    • 2014-04-17
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多