【问题标题】:Using an Array to make another Array in reverse order使用一个数组以相反的顺序制作另一个数组
【发布时间】:2016-02-03 07:19:23
【问题描述】:

这里真的需要一些帮助。我的 testList 是字母表的数组 [26]。我想使用一个循环来为 newList 做一个相反的顺序。

当我在循环内测试 newList 的输出时它可以工作,但如果我在循环外测试它就不行。如果有人可以帮助我,将不胜感激!

提前致谢。

 void CText::createList(){
        int i;
        int j;

        for (i = 0; i < 26; i++) {
            counter = 0;
            j = 25; 
            newList[j] = textList[i];
            j--;
           //cout << newList[j] << endl;

        }

        cout << newList[0] << endl;
    }

【问题讨论】:

  • 如果你声明char newList[25],那么点击newList[25]是越界的。
  • 你应该在循环之前设置一次j = 25;。将其作为拼写错误关闭。
  • 您标记为 C++,因此最好使用 std::vector。您可以使用反向迭代器来获得您想要的。
  • 如果没有毫无意义的ij 声明会更加明显。
  • 谢谢大家,一切都解决了。没有使用 Vector,因为它只是即将到来的 c++ 考试的修订问题,他们特别要求一个数组。但 Vector 似乎是处理此类事情的更好方法。再次感谢您的帮助。

标签: c++ arrays loops


【解决方案1】:
void CText::createList(){
    int i;
    for (i = 0; i < 25; i++) {
       newList[25-1-i] = textList[i];
    }
    cout << newList[0] << endl;
}

但是,对于您的问题,最好使用向量并使用反向迭代器。 示例:

#include <iostream>
#include <iterator>     
#include <vector>  
int main()
{
    std::vector<int> normal_vector{0,1,2,3,4,5,6,7,8,9};
    std::vector<int> reverse_vector(normal_vector.rbegin(),normal_vector.rend());

    for(auto const& item:normal_vector){
        std::cout << item << "\t";
    }
    std::cout << std::endl;
        for(auto const& item:reverse_vector){
        std::cout << item << "\t";
    }
}

Live Demo

【讨论】:

  • OP 说 array[25] 不是 i &lt; 26 未定义的行为吗?
  • 谢谢,这是一个比我的代码更简洁的代码,并且运行良好。此外,LogicStuff 将 j = 25 移到循环外的评论也有效,谢谢!
【解决方案2】:

或者你可以使用algorithm头文件算法reverse来做同样的事情

void CText::createList() {
    std::copy(textList, textList + 26, newList);
    std::reverse(newList, newList + 26);
    std::cout << newList[0] << std::endl;
}

【讨论】:

    【解决方案3】:

    你在循环中重新初始化j,所以它总是在最后保存字符。由于您在 lop 内的 cout 使用的是相同的 j,它被重新初始化,它似乎可以工作。试试这个:

    void CText::createList(){
    
        for (int i = 0, int j = 25; i < 26; i++, j--)
            newList[j] = textList[i];
    
        cout << newList[0] << endl;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-31
      • 2011-06-06
      相关资源
      最近更新 更多