基于 C++ 范围的 for 循环中的&符号

qed*_*qed 0 c++ reference

这是代码:

#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;

}
Run Code Online (Sandbox Code Playgroud)

这是改编自一本 C++ 教科书中的一些示例代码,故意处理 C 风格的字符串,所以请耐心等待。

所以我尝试了两个版本,一个for (auto c : buffer)带有for (auto &c : buffer). 两者似乎都有效。问题是,那有什么区别呢?

小智 5

当您使用链接时,您可以直接使用容器的元素。否则- 与副本。试试这个例子:

#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];
}
Run Code Online (Sandbox Code Playgroud)