【问题标题】:Vector "erase" and "at" producing an error (c++)矢量“erase”和“at”产生错误(c++)
【发布时间】:2016-06-06 17:38:41
【问题描述】:

我正在使用More elegant way to check for duplicates in C++ array? 中提供的算法来打印重复的元素。

   #include <random>
    #include <algorithm>
    #include <iterator>
    #include <iostream>
    
    using namespace std;
    
    
    /*Complexity: O(n log n). You sort once, then you iterate once*/
    void function_1(std::vector<int> t)
    {
      cout << "The duplicate elements are: \n";
      std::sort(t.begin(), t.end());
      for(int i = 0; i < t.size() - 1; i++)
      {
          if (t[i] == t[i + 1]) 
          {
          t.erase(t.at(i));
          i--;
          }
      }
    }
    
    
    int main()
    {
       std::vector<int> test{1,2,1,3,2,4};
    
       function_1(test);
      
      return 0;
    } 

问题

我在t.erase(t.at(i)); 收到以下错误

 error: no matching function for call to ‘std::vector<int>::erase(__gnu_cxx::__alloc_traits<std::allocator<int> >::value_type&)’
    t.erase(t.at(i));

我不明白为什么会出现上述错误。

谢谢

【问题讨论】:

  • vector::erase 需要什么类型的参数?您是否阅读了vector 的文档?
  • 注意:有符号无符号麻烦:` i + 1 i < t.size() - 1。但是,考虑一个无符号 i。
  • @OP FYI,test.erase(std::unique(test.begin(), test.end()), test.end()); 从已排序的向量中删除重复项。
  • 为了清楚起见,您从链接问题的答案中复制的代码中的擦除位是完全错误的。
  • 你确定这个算法是O(n log n)吗?在最坏的情况下(所有欺骗),您最终会在排序和迭代之上反复擦除和改组向量中的所有元素。不过,我想知道这种情况下排序阶段的负担是否会以某种方式抵消改组?

标签: c++ vector


【解决方案1】:

std::vector::erase 需要一个迭代器来指向您要擦除的位置。您正在提供对存储值的引用。

你可以:

t.erase(std::next(t.begin(), i));

【讨论】:

  • @Smeeheey 仍然不起作用。 std::advance 返回void。你想要的是std::next
  • 是的,再次正确,甚至更好
【解决方案2】:

vector::erase 需要一个迭代器——不是元素类型,所以你应该改变:

t.erase(t.at(i));

t.erase(t.begin() + i);

编译

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-19
    • 2021-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-07
    • 2017-06-04
    相关资源
    最近更新 更多