【问题标题】:How to sort a Vector and Remove the Same Value in it?如何对向量进行排序并删除其中的相同值?
【发布时间】:2013-05-25 14:49:19
【问题描述】:

我有一个包含数据的向量,例如:15,27,40,50,15,40

我想对其排序,去掉相同的值,所以排序后的输出应该是:15,27,40,50

我尝试了几种方法:

std::sort(vectProjHori.begin(),vectProjHori.end());
for (std::vector<int>::iterator it=vectProjHori.begin(); it!=vectProjHori.end(); ++it)
{
    if(it+1 != it)
    {
        std::cout << ' ' << *it;
    }
}

但是,它不能删除向量中的相同值。 我真的希望有人愿意提供一种有效的方法。

任何帮助将不胜感激。 谢谢

【问题讨论】:

    标签: c++ algorithm vector


    【解决方案1】:

    您可以使用标准函数来做到这一点。

    std::sort(vectProjHori.begin(), vectProjHori.end());
    vectProjHori.erase(std::unique(vectProjHori.begin(), vectProjHori.end()), vectProjHori.end());
    

    【讨论】:

    • 感谢@mwerschy,这是迄今为止最简单的方法。
    【解决方案2】:

    it + 1肯定不是it;您需要在比较之前先取消引用。

    【讨论】:

    • 愚蠢的我,我的错..我没有足够的意识..但我很沮丧,我不知道其他方法怎么做。
    【解决方案3】:

    这将完成您的工作,但上面 mwerschy 的代码更好。 C++11

    #include <iostream>
    #include <algorithm>
    #include <iterator>
    
    
    int main() { 
    
      std::vector<int> v={1,2,8,4,5,5};
      std::sort(v.begin(),v.end());
      auto it=std::unique(v.begin(),v.end());
      v.resize(std::distance(v.begin(),it));
      std::copy(v.begin(),v.end(),std::ostream_iterator<int>(std::cout,"\n"));
    
     }
    

    输出将是:

    1
    2
    4
    5
    8
    

    【讨论】:

    • 您可以使用resize 来做到这一点(尽管使用erase 似乎是更明显的选择),但是,不能使用这些参数。
    猜你喜欢
    • 2014-05-09
    • 1970-01-01
    • 1970-01-01
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多