使用Array以相反的顺序创建另一个Array

时间:2016-02-03 07:19:24

标签: c++ arrays loops

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

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

提前致谢。

 -(void)setProgressViewProgress
{
    //Check for completion
    if(progress > 1.0)
    {
        [self progressCompleted];
        return;
    }
    //Diffrent speed for range
    CGFloat speed;
    //From 0.000 to 0.500 speed is 500*0.007 = 3.5 seconds    0.007(sec) => x(sec) = Total time in range(sec) / 500.0 ==> 3.5/500.0 = 0.07
    if(progress<0.50)
    {
        speed = 0.007;
    }
    //From 0.500 to 0.750 speed is 250*0.005 = 1.25 seconds 0.005(sec) => x(sec) = Total time in range(sec) / 500.0 ==> 1.25/250.0 = 0.05
    else if(progress<0.75)
    {
        speed = 0.005;
    }
    //From 0.750 to 1.0 speed is 250*0.002 = 0.5 seconds 0.002(sec) => x(sec) = Total time in range(sec) / 500.0 ==> 0.5/250.0 = 0.02
    else
    {
        speed = 0.002;
    }
    //Increase the progress view by 1/1000  for smooth animation
    progress+=0.001;
    [progressView setProgress:progress];
    [self performSelector:@selector(setProgressViewProgress) withObject:nil afterDelay:speed];
}

3 个答案:

答案 0 :(得分:3)

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

但是,最好使用vector并使用反向迭代器来解决问题。 例如:

#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

答案 1 :(得分:2)

或者您可以使用algorithm头文件算法reverse来执行相同的操作

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

答案 2 :(得分:-1)

您正在循环中重新初始化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;
}