2010-03-07 21 views
2

VISUAL C++ Questioncomment déplacer les éléments du tableau à droite et remplacer l'index déplacé avec la chaîne dans Visual C++

Salut,

Je tableau de 3 éléments et je veux passer ses éléments à droite et remplacez la cellule d'index décalée par la chaîne "SHIFTED" et cela devrait boucler jusqu'à ce que toutes les cellules aient une chaîne "SHIFTED".


Par exemple:

int a[x]={0,1,2}; 

index initial et éléments de commande:

[0]=0 
[1]=1 
[2]=2 

devrait être dans le:

1ère boucle:

[0]=SHIFTED 
[1]=0 
[2]=1 

2ème boucle:

[0]=SHIFTED 
[1]=SHIFTED 
[2]=0 

3ème boucle:

[0]=SHIFTED 
[1]=SHIFTED 
[2]=SHIFTED 

Je sais que je peux le faire avec memmove() mais je ne veux pas utiliser une fonction en elle.

Pourriez-vous s'il vous plaît m'aider; voici mon travail:

#include <iostream> 
#include <string> 
#include <stdio.h> 
#include <cstdlib> 
using namespace std; 

int const ARRAY_SIZE=3; 

int main() 
{ 
int Array[ARRAY_SIZE]; 
int iniPostion,newPostion; 
string x="SHIFTED"; 
for(iniPostion=0; iniPostion<ARRAY_SIZE; iniPostion++) 
{ 
    Array[iniPostion] = iniPostion; 
    cout << "Cell [" << iniPostion << "] Initial Element is: (" << Array[iniPostion] << ")" << endl; 
} 
cout << endl; 
for(newPostion=0; newPostion<ARRAY_SIZE; newPostion++) 
{ 
    Array[newPostion]=newPostion; 
    cout << "Cell [" << newPostion << "]  New Element is: ("; 
    if(Array[newPostion-1]<0) 
    { 
    cout << x << ")\n"; 
    } 
    else 
    { 
    cout << Array[newPostion-1] << ")" << endl; 
    } 
} 
return 0; 
} 

Répondre

3

Comme Peter l'a mentionné dans sa réponse, vous ne pouvez pas affecter de chaîne à un int. J'ai supposé SHIFTED être -1.Donc, chaque fois que vous vous déplacez, vous apportez un -1 dans l'écart créé.

Vous avez besoin de deux boucles. Les boucles externes itère N (3) fois et la boucle intérieure commence à la fin du réseau et des copies (n-1)th élément à nth Position:

for(int count = 0;count < N;count++){ 
    for(newPostion=ARRAY_SIZE-1; newPostion > count;newPostion--) 
     Array[newPostion]=Array[newPostion - 1]; // copy 
    Array[newPostion]= -1; // fill the gap. 

    // print. 
    for(iniPostion=0; iniPostion<ARRAY_SIZE; iniPostion++) { 
     cout << "Cell [" << iniPostion << "] Initial Element is: (" << Array[iniPostion] << ")" << endl; 
    } 
    cout<<endl; 
} 

course de l'échantillon:

# g++ a.cpp && ./a.out 
Cell [0] Initial Element is: (0) 
Cell [1] Initial Element is: (1) 
Cell [2] Initial Element is: (2) 

Cell [0] Initial Element is: (-1) 
Cell [1] Initial Element is: (0) 
Cell [2] Initial Element is: (1) 

Cell [0] Initial Element is: (-1) 
Cell [1] Initial Element is: (-1) 
Cell [2] Initial Element is: (0) 

Cell [0] Initial Element is: (-1) 
Cell [1] Initial Element is: (-1) 
Cell [2] Initial Element is: (-1) 
+0

Merci beaucoup codaddict, qui a fait l'affaire :) Merci –

1

je tableau de 3 éléments et je veux changer ses éléments à droite et à remplacer la cellule d'index déplacé avec la chaîne « DÉCALÉE » et cela doit passer en boucle jusqu'à ce que toutes les cellules a Chaîne "SHIFTED"

Cela n'a aucun sens. Vous avez un tableau de nombres (entiers), qui bien sûr ne peut pas contenir une chaîne. Ce que vous pouvez faire est par ex. insérer 0 ou -1 pour désigner l'élément décalé.

Le changement lui-même peut être facilement mis en œuvre grâce à une opération std::rotate.

Mais puisque tous les éléments contiennent la même chose à la fin, pourquoi ne pas les assigner directement sans tout le décalage?

+0

oui vous avez raison, cela ne fait pas de sens: $ merci d'être passé :) –

2

Il est un peu difficile, comment vous pouvez vous attendre à avoir une chaîne ("SHIFTED") dans un tableau d'entiers.

Cependant, pour cette opération, vous pouvez utiliser l'algorithme rotate:

#include <iostream> 
#include <algorithm> 
#include <string> 

int const ARRAY_SIZE=3; 

void print(std::string* array) { 
    for (int i = 0; i != ARRAY_SIZE; ++i) { 
     std::cout << array[i] << ' '; 
    } 
    std::cout << '\n'; 
} 

int main() 
{ 
    std::string Array[ARRAY_SIZE] = {"0", "1", "2"}; 
    print(Array); 

    //the last item ends up at the beginning of the array 
    std::rotate(Array, Array + ARRAY_SIZE - 1, Array + ARRAY_SIZE); 

    //now overwrite the item that used to be last 
    Array[0] = "SHIFTED"; 
    print(Array); 
    return 0; 
} 

Il serait probablement plus simple et plus efficace avec un récipient approprié, tel que std::deque ou std::list où l'on pouvait pop_back la dernière valeur et push_front la nouvelle valeur.

+0

UcnleBens Great explication, merci –

0

Cette pue de devoirs ..

Y a-t-il une raison pour laquelle vous ne pouvez pas garder une trace du nombre de postes que vous avez effectués et en tenir compte lorsque vous imprimez?

#include <iostream> 

int const ARRAY_SIZE=3; 

class Shifter 
{ 
    public: 
     Shifter(const int* array_, size_t size_) 
     : array(array_), size(size_), shifts(0) {} 
     void Shift(size_t steps = 1) { shifts += steps; if(shifts > size) shifts = size; } 
     void Print(std::ostream& os) const; 
    private: 
     const int* array; 
     size_t size; 
     size_t shifts; 
}; 

void Shifter::Print(std::ostream& os) const 
{ 
    for(size_t i = 0; i < size; ++i) 
    { 
     os << "Cell [" << i << "] = "; 
     if(i < shifts) 
      os << "SHIFTED"; 
     else 
      os << array[i - shifts]; 
     os << std::endl; 
    } 
} 

std::ostream& operator <<(std::ostream& os, const Shifter& sh) 
{ 
    sh.Print(os); 
    return os; 
} 

int main(void) 
{ 
    // Initialize the array. 
    int a[ARRAY_SIZE]; 
    for(size_t iniPostion=0; iniPostion < ARRAY_SIZE; iniPostion++) 
     a[iniPostion] = iniPostion; 
    Shifter sh(a, ARRAY_SIZE); 
    std::cout << "Initial contents:" << std::endl; 
    std::cout << sh << std::endl; 

    // Do the shifts. 
    for(size_t newPostion = 0; newPostion < ARRAY_SIZE; newPostion++) 
    { 
     std::cout << "Shift by 1..." << std::endl; 
     sh.Shift(); 
     std::cout << sh << std::endl; 
    } 

    return 0; 
} 
+0

Mike D: –

1

Voici ma solution simple dans la plaine ancienne C

#include <stdio.h> 
#include <stdlib.h> 
void main(int argc, char **argv) { 

    int MAX_LEN = 11; 
    int numOfShifts = 1; 
    if (argc > 1) { 
     numOfShifts = atoi(argv[1]); 
    } 
    printf("Number of shifts = %d\n",numOfShifts); 

    int arr[] = { 0,1,2,3,4,5,6,7,8,9,10 }; 
    int i; 
    int n; // number of shifts index 

    for (n = 0; n < numOfShifts; n++) { 
     for (i = MAX_LEN - 1; i >= 0; i--) { 
      if (i == 0) { 
       arr[i] = -1; 
      } else { 
       arr[i] = arr[i-1]; 
      } 
     } 
    } 

    // output 
    for(i = 0; i < MAX_LEN; i++) { 
     printf("Arr[%d] = %d\n", i, arr[i]); 
    } 

} 
+0

parfait, merci –

0

Vous pouvez simple mémoire de déplacement.

// shift down 
int a[ 10 ]; 
memmove(a, a +1, sizeof(a) -sizeof(a[ 0 ]));