C++ vector中的唯一值

rqenqsqc  于 11个月前  发布在  其他
关注(0)|答案(4)|浏览(112)

我必须创建一个程序,要求用户输入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] << " ";
}

字符串
我想感谢大家的帮助。

c6ubokkw

c6ubokkw1#

可以使用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));

字符串

m0rkklqb

m0rkklqb2#

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

yx2lnoni

yx2lnoni3#

我的解决方案,下面,试图改变代码尽可能少(增加4行)。我已经运行在命令行。
请注意,就在语句'cin >> x'之后,我添加了一个测试来确定输入的整数是否已经在vector v中。如果测试成功,则放弃将输入的整数添加到vector的可能性,其影响与其超出范围类似。
注意,<algorithm>必须包含在find中。
由于有点生疏,我在网上做了一个快速搜索,使用“c++ vector test membership”(当然没有引号:-)作为搜索词。
我假设性能还不是一个优先考虑的问题,但是如果向量的大小远远大于20,它可能值得一个散列(显然有类似的<algorithm>变体),提供更多的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] << " ";
}

字符串

v8wbuo2f

v8wbuo2f4#

简单:

sort(vec.begin(), vec.end());
vec.erase(unique(vec.begin(), vec.end()), vec.end());

字符串

相关问题