2015-07-11 38 views
1

假設,如果我們有兩個整數數組a1[2]a2[2],我們要採取輸入,所以我們一般做的是這樣我們可以在數組(a1,a2)中進行輸入嗎?

int a1[2],a2[2]; 
int i; 
cout<<"Enter values in array a1\n"; 
for(i=0;i<2;i++) 
{ 
    cin>>a1[i];  // Taking input in a1 separatly using loop 
} 
cout<<"Enter values in array a2\n"; 
for(i=0;i<2;i++) 
{ 
    cin>>a2[i];  // Taking input in a2 separatly using loop 
} 

但是,我們可以做這樣的事情使用代碼CIN語句,儘量減少..

for(j=1;j<3;j++) // Loop for taking input in a(j) array , value of j will be 1 first time so that input will be in array a1 
{ 
    cout<<"Enter values in array a"<<j<<endl; 
    for(i=0;i<2;i++) 
    { 
     cin>>a(j)[i]; // Can we do something like this so that we can take input using a loop inside loop 
    } 
} 

我不知道什麼應該是正確的問題標題,所以任何想編輯問題標題的人都可以做。

+0

是的,有' std :: map'來支持這樣的。 –

回答

1

你的意思是像下面這樣的東西嗎?

#include <iostream> 
#include <functional> 

int main() 
{ 
    const size_t N = 2; 
    int a1[N]; 
    int a2[N]; 
    size_t j = 1; 

    for (auto &r : { std::ref(a1), std::ref(a2) }) 
    { 
     std::cout << "Enter values in array a" << j++ << ": "; 
     for (size_t i = 0; i < N; i++) 
     { 
      std::cin >> r.get()[i]; 
     } 
    }   

    for (auto &r : { std::ref(a1), std::ref(a2) }) 
    { 
     for (size_t i = 0; i < N; i++) std::cout << r.get()[i] << ' '; 
     std::cout << std::endl; 
    }   
}  

如果進入

1 2 3 4 

那麼輸出將看起來像

Enter values in array a1: 1 2 
Enter values in array a2: 3 4 
1 2 
3 4 

使用這種方法,你可以使用僅僅兩個陣列的更多。例如

const size_t N = 2; 
    int a1[N]; 
    int a2[N]; 
    int a3[N]; 
    int a4[N]; 
    size_t j = 1; 

    for (auto &r : { std::ref(a1), std::ref(a2), std::ref(a3), std::ref(a4) }) 
    //... 
+0

thnx,它的工作! – udit043

1

如果你想保持2個獨立的陣列,可以做到以下幾點:

for(j=1;j<=2;j++) // Loop for taking input in a(j) array , value of j will be 1 first time so that input will be in array a1 
{ 
    cout<<"Enter values in array a"<<j<<endl; 
    for(i=0;i<2;i++) 
    { 
     cin>>(j == 1 ? a1[i] : a2[i]); 
    } 
} 

如果它是沒有問題的,你有1個陣列,您可以執行以下操作使用2維數組:

int a[2][2] 
for(int i=0; i<=1; i++) 
{ 
    cout << "Enter values for a[" << i << "][j]" << endl; 
    for(int j=0; j<=1; j++) 
    { 
     cin >> a[i][j]; 
    } 
} 
0

這裏a1和a2是數組變量名稱。我懷疑你能否做到這一點。 我在想什麼,我們能做些什麼來解決你點是一樣的東西

  1. 構造CPP語句字符串
  2. execute string as cpp code inside program 我不覺得這樣做很簡單,雖然
相關問題