2013-09-25 55 views
-1

我正在創建一個C++數組程序,我試圖從用戶獲取輸入,但在插入過程中我想提示用戶輸入重複值。我已經使用了while循環和for循環,但如果用戶輸入重複值,則不起作用。他將被要求在特定指數處再次輸入數值。如何在插入C++數組時刪除重複的條目

int size=0; 
int k; 
int index=0; 
int temp=0; 
int aray1[2]; 
char ch='y'; 
while(ch='y') { 
    for(k=0; k<=2; k++) 
    { 
     if(aray1[k]==temp) { 
      cout<<"please do not enter duplicates"; 
      ch='y'; 
      index--; 
     } else { 
      aray1[index]=temp; 
      index++ 
      ch='n'; 
     } 


    } 

    system("pause"); 
} 
+0

將數組是長度爲2只 –

+0

爾加,這違反了縮進我的眼睛。至少有一個閉合花括號('}')缺失。或者你真的在每個'while'迭代中使用'system(「pause」)'? – Zeta

+0

哇,在while(ch ='y')'中缺少一個等號,你正在讀取'aray1'的第三個元素,你正在比較未初始化的值('aray1 [k] == temp')。 。 – Michael

回答

2

我會使用std::vector來代替。

#include<iostream> 
#include<vector> 
#include<algorithm> 

int main(){ 
    using namespace std; 
    vector<int> v; 

    int size=2;  

    while(v.size()<size){ 
    int i; 
    cin >> i; 
    vector<int>::iterator it = find(v.begin(), v.end(), i); 

    if(it==v.end()) // i is not in v so insert it to the end of the vector. 
     v.push_back(i); 
    else 
     cout << "Duplicate entered." << endl; 
    } 
} 

http://www.cplusplus.com/reference/algorithm/find/

+0

或者只是使用'std :: set',它只存儲唯一值... – RedX

+0

是的,他最好使用std :: unordered_set,根據insert操作的返回值報告「duplicate」,然後收集元素到一個矢量,但我只是想給他一個最簡單的基本解決方案。 –

+0

關鍵是他不需要一個'vector',也不需要'unordered_set'一個常規集合將完美地滿足他的需求。 – RedX