我必须创建一个程序,要求用户输入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] << " ";
}
字符串
我想感谢大家的帮助。
4条答案
按热度按时间c6ubokkw1#
可以使用
std::unique
:http://www.cplusplus.com/reference/algorithm/unique/?kw=unique
字符串
m0rkklqb2#
你可以使用
std::set
或std::unordered_set
来跟踪你已经看到的值。具体来说,insert
方法将返回值是否已经插入到集合中。然后,如果值是新的,你只会将值推入向量。yx2lnoni3#
我的解决方案,下面,试图改变代码尽可能少(增加4行)。我已经运行在命令行。
请注意,就在语句'cin >> x'之后,我添加了一个测试来确定输入的整数是否已经在vector v中。如果测试成功,则放弃将输入的整数添加到vector的可能性,其影响与其超出范围类似。
注意,
<algorithm>
必须包含在find中。由于有点生疏,我在网上做了一个快速搜索,使用“c++ vector test membership”(当然没有引号:-)作为搜索词。
我假设性能还不是一个优先考虑的问题,但是如果向量的大小远远大于20,它可能值得一个散列(显然有类似的
<algorithm>
变体),提供更多的log(n)搜索时间而不是线性搜索时间。字符串
v8wbuo2f4#
简单:
字符串