gpt4 book ai didi

c++ - 使用引用指针中的信息填充 vector

转载 作者:行者123 更新时间:2023-12-02 10:37:05 26 4
gpt4 key购买 nike

我的目标是建立一个接受整数列表并将其相互比较的函数。基本上,如果当前位置之前和之后的位置中的数字匹配,则当前数字变为(或保持)0。否则,它变为(或保持)1。

代码必须假定第一个值和最后一个值之后为零,这就是为什么在for循环之外有那些“if-else”语句的原因。更新必须一次完成,这就是为什么要有第二个 vector 来存储新值(x)的原因,而主 vector (houses)将被设置为最后一个值。

我的计划是采用传递给函数的值,并用它们填充 vector 。但是,我从未见过这样的事情(即使距离我的学士学位还不到3个月……谢谢,斯特雷耶)。

如何用存储在引用内存位置中的列表填充 vector ?

注意:

  • 我使用cout << *states;来尝试查看引用位置时的代码,当我意识到该位置不起作用时,但返回的都是一个整数。有人可以帮助我了解它的工作原理以及如何用值填充 vector 吗?
  • 另外,我知道使用push_back()而不是.at(i)=方法会更有效,但是我只是尽我所能找出问题所在,并在我放弃时解决了。)
  • vector<int> cellCompete(int* states, int days) 
    {
    vector<int> houses;
    vector<int> x;
    x.resize(8);
    cout << *states;
    for (unsigned int i = 0; i<8; i++){
    houses.push_back(*states);
    cout << houses.at(i) << endl;
    }
    for (unsigned int i = 0; i<days; ++i) {
    if (houses.at(1)==0) {
    x.at(0)=0;
    }
    else{
    x.at(0)=1;
    }
    for (unsigned int y=1; y<7; y++){
    if (houses.at(y-1)==houses.at(y+1)){
    x.at(y)=0;
    }
    else{
    x.at(y)=1;
    }
    }
    if (houses.at(6)==0){
    x.at(7)=0;
    }
    else{
    x.at(7)=1;
    }
    houses=x;
    }
    return houses;
    }

    最佳答案

    My goal is to build a function that takes a list of integers and compares them to each other.



    阅读您的代码后,我了解到“整数列表”实际上是作为指针传递的数组,而天数就是该数组中整数的数量:
    vector<int> cellCompete(int* states, int days)  

    不幸的是,在循环中,您总是附加到 vector *state,在这种情况下,它将是整数的第一个数组。如果指针指向数组,则可以将其递增以指向下一个元素,也可以像对数组那样进行索引:
    vector<int> houses;
    vector<int> x(8); // you can get the right size at construction
    for (unsigned int i = 0; i<8; i++){
    houses.push_back(states[i]);
    cout << houses[i] << endl;
    }

    我无法回答这个问题:是否有理由使用 8的硬编码大小?应该不是 days吗?

    带着这个提示,我将剩下的练习留给您,以促进您的学习经验;-)

    关于c++ - 使用引用指针中的信息填充 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59829245/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com