【问题标题】:C++ Unique values in a vector?C ++向量中的唯一值?
【发布时间】:2014-11-09 02:16:03
【问题描述】:

我必须创建一个程序,要求用户输入 10 到 100 之间的 20 个数字,这些数字将存储在向量中,但只会存储唯一值。我创建了一个程序来存储范围内的值,但我不知道如何只存储唯一值。这是我所拥有的:

#include <iostream>
#include <vector>
using namespace std;

void print(vector<int>v);

int main()
{
    vector<int>v;


    int x;
    for (int num = 0; num < 20; num++)
    {
        cout << "Enter number " << (num + 1) << ":";
        cin >> x;
        if (10 < x)
        {
            if (x < 100)

                v.push_back(x);
        }
    }
    print(v);


}

void print(vector<int>v2)
{
    for (int count = 0; count < v2.size(); count++)
    cout << v2[count] << " ";
}

感谢大家的帮助。

【问题讨论】:

  • 为什么您的印刷版会复制整个矢量?那是不必要的。而是通过 const 引用传递。
  • 如果必须使用vector,则在插入前使用std::find函数检查该值是否已经存在。
  • 你为什么不直接使用 std::set?

标签: c++ vector unique


【解决方案1】:

你可以使用std::unique:

http://www.cplusplus.com/reference/algorithm/unique/?kw=unique

using namespace std;

vector<int> v;
int x;

for (int num = 0; num < 20; num++)
{
    cout << "Enter number " << (num + 1) << ":";
    cin >> x;
    if (10 < x)
    {
        if (x < 100)

            v.push_back(x);
    }
}

sort(v.begin(), v.end());
vector<int>::iterator it;
it = unique(v.begin(), v.end());  

v.resize(distance(v.begin(),it));  

【讨论】:

  • 虽然链接页面说的很清楚,但这里可能值得一提的是,使用排序需要#include &lt;algorithm&gt;,距离需要#include &lt;iterator&gt;
【解决方案2】:

您可以使用std::setstd::unordered_set 来跟踪您已经看到的值。具体来说,insert 方法将返回该值是否已经插入到集合中。然后,如果值是新的,则仅将值推入向量中。

【讨论】:

    【解决方案3】:

    下面我的解决方案尝试尽可能少地更改代码(添加了 4 行)。我已经在命令行上运行了。

    请注意,在语句 'cin >> x' 之后,我添加了一个测试以确定输入的整数是否已经在向量 v 中。如果测试成功,那么可能将输入的整数添加到向量中被遗弃,其影响与超出范围类似。

    另外请注意,必须包含 &lt;algorithm&gt; 才能使用 find。

    由于有点生疏,我在网上进行了快速搜索,使用“c++ 矢量测试成员资格”(当然不带引号 :-) 作为搜索词。

    我认为性能还不是一个优先问题,但如果向量大小远大于 20,它可能值得一个哈希(显然有可比的 &lt;algorithm&gt; 变体),给出更多的 log(n)搜索时间比线性搜索时间。

    #include <iostream>
    #include <vector>
    #include <algorithm>
    using namespace std;
    
    void print(vector<int>v);
    
    int main()
    {
        vector<int>v;
    
    
        int x;
        for (int num = 0; num < 20; num++)
        {
            cout << "Enter number " << (num + 1) << ":";
            cin >> x;
            if (find(v.begin(), v.end(), x) != v.end()) {
                continue;
            }
            if (10 < x)
            {
                if (x < 100)
    
                    v.push_back(x);
            }
        }
        print(v);
    
    
    }
    
    void print(vector<int>v2)
    {
        for (int count = 0; count < v2.size(); count++)
        cout << v2[count] << " ";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-03
      • 2020-03-26
      • 1970-01-01
      • 2020-05-29
      • 2019-09-25
      • 2012-03-13
      • 1970-01-01
      相关资源
      最近更新 更多