2014-11-09 51 views
0

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

#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] << " "; 
} 

我想感谢大家的帮助。

+1

为什么你的印刷版复制整个向量?这是不必要的。改为传递const引用。 – 2014-11-09 02:58:33

+1

如果必须使用向量,那么在插入之前使用'std :: find'函数检查值是否已经存在。 – 2014-11-09 02:59:05

+0

为什么你不使用std :: set? – paulm 2014-11-09 18:10:09

回答

0

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

1

我的解决方案试图尽可能少地改变代码(增加4行)。我已经在命令行上运行了这个。

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

请注意,<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] << " "; 
} 
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));