2017-09-08 53 views
-4

這裏的範圍是代碼:與號在基於C++的for循環

#include <cmath> 
#include <iostream> 
#include <iomanip> 
#include <vector> 
#include <cstdio> 

int main(int argc, char *argv[]) { 
    const unsigned int max_chars = 100; 
    char buffer[max_chars]; 
    std::cin.getline(buffer, max_chars, '\n'); 
    unsigned int count = 0; 
    for (auto c : buffer) { 
     if (c == '\0') { 
      break; 
     } 
     count++; 
    } 
    std::cout << "Input: ===========" << std::endl; 
    std::cout << buffer << std::endl; 
    std::cout << "Number of chars ==" << std::endl; 
    std::cout << std::dec << count << std::endl; 
    std::cout << "==================" << std::endl; 

} 

這是改編自刻意處理C風格的字符串一個C++教科書一些示例代碼,所以大家多多包涵。

所以我試了兩個版本,一個用for (auto c : buffer),另一個用for (auto &c : buffer)。兩者似乎都有效。問題是,那麼有什麼不同呢?

+2

在第一種情況下,您會得到每個元素的副本,第二種情況下您將獲得對該元素的引用。 – rustyx

+5

一個是對數組中的值的引用,另一個是它的副本。但說實話,如果你正在問這樣的事情,你需要從初學者的C++書中讀到更多,完全解釋這一點,並且你需要的所有上下文遠遠超出了作爲答案的範圍。 –

+0

@qed是你的問題「什麼是參考」或「這種特定類型有什麼區別」? – fukanchik

回答

1

當您使用鏈接時,您直接使用容器的元素。否則 - 一份副本。試試這個例子:

#include <iostream> 
#include <vector> 
using namespace std; 

int main() 
{ 
    int n = 10; 
    vector<int> a(n); 
    vector<int> b(n); 
    for (auto &key : a) key = rand()%10; 
    for (auto key : b) key = rand()%10; 
    for (int i = 0; i < n; i++) cout << a[i]; 
    cout << endl; 
    for (int i = 0; i < n; i++) cout << b[i]; 
} 
3

第一個(沒有&)是一個值,第二個(與&)是一個參考。顧名思義,引用「引用」一個值,類似於指針「指向」值的方式。

嘗試在if語句後添加c = 'x';並嘗試兩種方法來查看這裏的區別。