基于循环的C 范围内的Ampers和

Ampersand in c++ range based for loops

本文关键字:范围内 Ampers 于循环 循环      更新时间:2023-10-16

这是代码:

#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 == '') {
            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)。两者似乎都起作用。问题是,那是什么区别?

使用链接时,您可以直接与容器的元素一起使用。否则 - 带有副本。尝试此示例:

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

第一个(no&amp;)是一个值,第二个(with&amp;)是参考。顾名思义,引用"引用"值,类似于指针"点"值的方式。

尝试在您的if语句之后添加c = 'x';,并尝试在此处查看差异。