我必须创建一个程序,要求用户输入 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] << " ";
}
我要感谢大家的帮助。
您可以使用
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));
您可以使用
std::set
或 std::unordered_set
来跟踪您已经看到的值。具体来说, insert
方法将返回该值是否已插入到集合中。然后,仅当该值是新值时,才将其推入向量中。
我的解决方案如下,尝试尽可能少地更改代码(添加了 4 行)。我已经在命令行上运行了这个。
请注意,在语句“cin >> x”之后,我添加了一个测试来确定输入的整数是否已经在向量 v 中。如果测试成功,则放弃将输入的整数添加到向量中的可能,与超出范围具有类似的影响。
另请注意,必须包含
<algorithm>
才能使用 find。
由于有点生疏,我在网上进行了快速搜索,使用“c ++向量测试成员资格”(当然不带引号:-)作为搜索词。
我假设性能还不是优先考虑的问题,但如果向量大小远大于 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] << " ";
}
简单:
sort(vec.begin(), vec.end());
vec.erase(unique(vec.begin(), vec.end()), vec.end());