我必须创建一个程序,要求用户输入 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 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));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)