elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Curso de javascript por TickTack


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación C/C++ (Moderadores: Eternal Idol, Littlehorse, K-YreX)
| | |-+  intercambiar valores dentro de un vector
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: intercambiar valores dentro de un vector  (Leído 3,999 veces)
bash

Desconectado Desconectado

Mensajes: 258



Ver Perfil
intercambiar valores dentro de un vector
« en: 20 Enero 2016, 20:31 pm »

Un saludo a todos !!

tengo una duda , yo quiero intercambiar valores dentro de un vector , pero cada vez que accedo a algun elemento usando un objeto temporal recibo un error , vi la funcion std::swap pero ella intercambia entre dos vectores y yo solo tengo uno estoy pensando probar con algun iterador pero me gustaria saber su opinion.

abajo dejo el codigo aunque es algo sencillo :D

Código
  1.  
  2. void SwapVectorValue(vector<Tile *>&ref,int index1, int index2)
  3. {
  4.   Tile *temp  = NULL;
  5.   temp->x     = ref[index1]->x;
  6.   temp->y     = ref[index1]->y;
  7.   temp->color = ref[index1]->color;
  8.   temp->index = ref[index1]->index;
  9.  
  10.   ref[index1]->x     = ref[index2]->x;
  11.   ref[index1]->y     = ref[index2]->y;
  12.   ref[index1]->color = ref[index2]->color;
  13.   ref[index1]->index = ref[index2]->index;
  14.  
  15.   ref[index2]->x         = temp->x;
  16.   ref[index2]->y         = temp->y;
  17.   ref[index2]->color     = temp->color;
  18.   ref[index2]->index     = temp->index;
  19.  
  20. }
  21.  
  22.  


gracias por su pronta respuesta...!!


En línea

gracias por responder mis dudas
ivancea96


Desconectado Desconectado

Mensajes: 3.412


ASMático


Ver Perfil WWW
Re: intercambiar valores dentro de un vector
« Respuesta #1 en: 20 Enero 2016, 20:44 pm »

temp en ese código es, como bien ahs puesto, NULL, y no un Tile.

Si trabajas con un vector de punteros, lo ideal, salvo que requieras lo contrario, es que intercambies los punteros, y no todos los campos de las estructuras a las que apuntan.
Para ello, bastaría un:
Código
  1. Tile* temp = ref[index1];
  2. ref[index1] = ref[index2];
  3. ref[index2] = temp;


En línea

bash

Desconectado Desconectado

Mensajes: 258



Ver Perfil
Re: intercambiar valores dentro de un vector
« Respuesta #2 en: 20 Enero 2016, 21:22 pm »

waooo que sencillo ,gracias aunque me gustaria decir que funcion realmente no
bueno voy a descansar dejare , el codigo completo aqui.


Código
  1. //============================================================================
  2. // Description : Hello World in C++, Ansi-style
  3. //============================================================================
  4.  
  5. #include <SDL2/SDL.h>
  6.  
  7. #include <map>
  8. #include <iostream>
  9. #include <string>
  10. #include <cstdlib>
  11. #include <ctime>
  12. /*para probar*/
  13. #include <vector>
  14. using namespace std;
  15.  
  16.  
  17. #define RED        0
  18. #define GREEN      1
  19. #define BLUE       2
  20. #define YELLOW     4
  21. #define GRAY       5
  22. #define NONE       6
  23. #define COLOR_QTY  5
  24. #define NOINDEX    -9999
  25.  
  26. SDL_Window   *window = nullptr;
  27. SDL_Renderer *render = nullptr;
  28. int **board  =nullptr;
  29. static int width  = 400;
  30. static int height = 500;
  31.  
  32. SDL_Rect cursor_pos ={0,0,16,16};
  33.  
  34. static int block_size;
  35. static int block_height;
  36. static int nCol   = 0;
  37. static int nRow   = 0;
  38.  
  39. /**Touch and movement*/
  40. static bool oneTimeClicked = true;
  41. static int o1 = NOINDEX;
  42. static int o2 = NOINDEX;
  43. static int getCollide;
  44.  
  45.  
  46.  
  47.  
  48. char title[32];
  49. bool Run  = false;
  50. SDL_Event event;
  51.  
  52.  
  53.  
  54.  
  55. string color_name []=
  56. {
  57. "red",
  58. "green",
  59. "blue",
  60. "yellow",
  61. "gray"
  62.  
  63. };
  64.  
  65. const char *filename[] =
  66. {
  67.  "red.bmp",
  68.  "green.bmp",
  69.  "blue.bmp",
  70.  "yellow.bmp",
  71.  "gray.bmp"
  72.  
  73. };
  74.  
  75.  
  76. SDL_Color color[]=
  77. {
  78. {0xff, 0,0,0xff},
  79. {0, 0xff,0,0xff},
  80. {0, 0,0xff,0xff},
  81. {0xff, 0xff,0,0xff},
  82. {0x90, 0x90,0x90,0xff}
  83. };
  84.  
  85. struct Tile
  86. {
  87.  
  88.   int x;
  89.   int y;
  90.   int color;
  91.   int index;
  92.   Tile(int x_,int y_, int color_ ,int indexVal)
  93.   :x(x_),y(y_), color(color_), index(indexVal){}
  94.   SDL_Rect getRect()
  95.   {
  96.   SDL_Rect rect ={x,y,block_size, block_height};
  97.   return rect;
  98.   }
  99. };
  100.  
  101.  
  102. map<string, SDL_Texture *>texture_list;
  103. vector<Tile *>tile_set;
  104.  
  105.  
  106. void CreateBlocks();
  107. void AlignBlocks();
  108. void CreateBoard();
  109. void DrawBoard();
  110. bool check_collision( SDL_Rect A, SDL_Rect B);
  111. void SwapVectorValue(vector<Tile *>&ref,int index1, int index2);
  112. int isCollide();
  113.  
  114. void CopiarTile(vector<Tile*> &tile, int index1,int index2);
  115.  
  116.  
  117.  
  118.  
  119. int main(int argc, char *argv[])
  120. {
  121.  
  122.  
  123.  
  124.  
  125.  
  126. SDL_Init(SDL_INIT_EVERYTHING);
  127.  
  128.  
  129.  
  130.  
  131. window = SDL_CreateWindow("table", SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,
  132.                   width, height, SDL_WINDOW_SHOWN|SDL_WINDOW_BORDERLESS);
  133.    render = SDL_CreateRenderer(window, -1 , SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
  134.  
  135.  
  136.    CreateBlocks();
  137. AlignBlocks();
  138. CreateBoard();
  139.  
  140.  
  141.    Run = (render == NULL  ? false : true);
  142.    while(Run)
  143.    {
  144.     while(SDL_PollEvent(&event))
  145.     {
  146.     if(event.type ==SDL_QUIT)
  147.     {
  148.     Run = false;
  149.     }
  150.     if(event.type == SDL_MOUSEMOTION)
  151.     {
  152.     cursor_pos.x = event.motion.x;
  153.     cursor_pos.y = event.motion.y;
  154.     }
  155.            if(event.type == SDL_MOUSEBUTTONDOWN)
  156.            {
  157.                getCollide  = isCollide();
  158.             if( getCollide != NOINDEX && oneTimeClicked == true)
  159.                   {
  160.                       o1 =getCollide;
  161.                      /// cout <<"el indice seleccionado es : "<<tile_set[o2]->index<<endl;
  162.                       oneTimeClicked = false;
  163.                    }
  164.             else if(getCollide != NOINDEX && oneTimeClicked == false)
  165. {
  166.                o2 = getCollide;
  167.                //cout <<"El segundo es este"<<tile_set[o2]->index<<endl;
  168.                 SwapVectorValue(tile_set,o1, o2);
  169.                 oneTimeClicked = true;
  170.                 o1 = NOINDEX;
  171.                 o2 = NOINDEX;
  172. }
  173.  
  174.  
  175.            }
  176.  
  177.  
  178.     }
  179.     const Uint8* key = SDL_GetKeyboardState(NULL);
  180. if(key[SDL_SCANCODE_Q])
  181. {
  182. Run = false;
  183. }
  184.  
  185.  
  186.  
  187.  
  188.       SDL_SetRenderDrawColor(render, 0x0,0x0,0x0, 0xff);
  189.       SDL_RenderClear(render);
  190.       DrawBoard();
  191.       SDL_RenderPresent(render);
  192.  
  193.    }
  194.    SDL_DestroyRenderer(render);
  195.    SDL_DestroyWindow(window);
  196.    SDL_Quit();
  197.  
  198.  
  199. return 0;
  200. }
  201.  
  202.  
  203.  
  204.  
  205.  
  206.  
  207.  
  208.  
  209.  
  210. void CreateBlocks()
  211. {
  212.   SDL_Surface* SurfaceTemp[COLOR_QTY] = {nullptr};
  213.   for(int i(0); i < COLOR_QTY ;i++)
  214.   {
  215.   SurfaceTemp[i] = SDL_LoadBMP(filename[i]);
  216.   /*if(SurfaceTemp[i] == NULL) {
  217.           fprintf(stderr, "CreateRGBSurface failed: %s\n", SDL_GetError());
  218.           exit(1);
  219.       }*/
  220.   }
  221.   for(int i(0); i < COLOR_QTY ;i++)
  222.      {
  223.     SDL_SetColorKey(SurfaceTemp[i],SDL_TRUE ,SDL_MapRGB(SurfaceTemp[i]->format,0,0,0));
  224.       texture_list[color_name [i]] = SDL_CreateTextureFromSurface(render ,SurfaceTemp[i]);
  225.       SDL_FreeSurface( SurfaceTemp[i]);
  226.      }
  227.   SDL_Surface *cursor = SDL_LoadBMP("cursor.bmp");
  228.   SDL_SetColorKey(cursor,SDL_TRUE ,SDL_MapRGB(cursor->format,0,0,0));
  229.   texture_list["cursor"] = SDL_CreateTextureFromSurface(render ,cursor);
  230.   SDL_FreeSurface(cursor);
  231.  
  232. }
  233.  
  234.  
  235. void AlignBlocks()
  236. {
  237. srand(time(nullptr));
  238.  
  239.  block_size   = 48;
  240.  block_height = block_size-3;
  241.  for(int i(0); i < height; i += block_size)
  242.  {
  243.  cout << " i [ "<< i<< "]\n";
  244.  nRow++;
  245.  }
  246.  for(int k(0);k < width; k +=block_size)
  247.  {
  248.  cout << " k [ "<< k<< "]\n";
  249.  nCol++;
  250.  }
  251.  board = new int*[nRow];
  252.  for(int o(0); o < nRow; o++)
  253.    board[o] = new int[nCol];
  254.  
  255.    for(int iter1(0); iter1<nRow; iter1++)
  256.    {
  257.     for(int iter2(0); iter2<nCol; iter2++)
  258.     {
  259.              board[iter1][iter2] = rand() % YELLOW + RED;
  260.              cout <<"||" <<board[iter1][iter2]<<"||";
  261.     }
  262.     cout <<"\n";
  263.    }
  264.  
  265. }
  266.  
  267.  
  268.  
  269.  
  270. void CreateBoard()
  271. {
  272.  
  273.    static int index = 0;
  274. int x = 32;
  275. int y = 32;
  276.  for(int iter1(0); iter1<nRow; iter1++)
  277.    {
  278.    index++;
  279.     for(int iter2(0); iter2<nCol; iter2++)
  280.     {
  281.  
  282.              Tile *temp = new Tile(x ,y,board[iter1][iter2],index);
  283.              ::tile_set.push_back(temp);
  284.              if(x >=(width -48*2))
  285.              {
  286.              x = 32;
  287.              if(y <= width)
  288.                   y +=45;
  289.              else if(y >= height )
  290.              {
  291.              cout <<"Sorry \n";
  292.              break;
  293.              }
  294.              }
  295.              else
  296.              {
  297.  
  298.              x +=48;
  299.              }
  300.  
  301.  
  302.     cout <<"x : "<< x <<" Y :" << y <<endl;
  303.     }
  304.     cout <<"-------------------------------------------------------------------"<<endl;
  305.    }
  306.  
  307. }
  308.  
  309. void DrawBoard()
  310. {
  311.  for(unsigned int f = 0; f < tile_set.size(); f++)
  312.  {
  313. SDL_Rect rect ={tile_set[f]->x,tile_set[f]->y,block_size, block_height };
  314. SDL_RenderCopy(render, texture_list[color_name[tile_set[f]->color]],NULL,&rect );
  315. SDL_RenderCopy(render, texture_list["cursor"],NULL,&cursor_pos );
  316.  }
  317. }
  318.  
  319.  
  320. bool check_collision( SDL_Rect A, SDL_Rect B )
  321. {
  322.    //The sides of the rectangles
  323.    int leftA, leftB;
  324.    int rightA, rightB;
  325.    int topA, topB;
  326.    int bottomA, bottomB;
  327.  
  328.    //Calculate the sides of rect A
  329.    leftA = A.x;
  330.    rightA = A.x + A.w;
  331.    topA = A.y;
  332.    bottomA = A.y + A.h;
  333.  
  334.    //Calculate the sides of rect B
  335.    leftB = B.x;
  336.    rightB = B.x + B.w;
  337.    topB = B.y;
  338.    bottomB = B.y + B.h;
  339.    //If any of the sides from A are outside of B
  340.        if( bottomA <= topB )
  341.        {
  342.            return false;
  343.        }
  344.  
  345.        if( topA >= bottomB )
  346.        {
  347.            return false;
  348.        }
  349.  
  350.        if( rightA <= leftB )
  351.        {
  352.            return false;
  353.        }
  354.  
  355.        if( leftA >= rightB )
  356.        {
  357.            return false;
  358.        }
  359.  
  360.        //If none of the sides from A are outside B
  361.        return true;
  362. }
  363.  
  364. void SwapVectorValue(vector<Tile *>&ref,int index1, int index2)
  365. {
  366.  /* Tile *temp  = NULL;
  367.    temp->x     = ref[index1]->x;
  368.    temp->y     = ref[index1]->y;
  369.    temp->color = ref[index1]->color;
  370.    temp->index = ref[index1]->index;
  371.  
  372.    ref[index1]->x     = ref[index2]->x;
  373.    ref[index1]->y     = ref[index2]->y;
  374.    ref[index1]->color = ref[index2]->color;
  375.    ref[index1]->index = ref[index2]->index;
  376.  
  377.    ref[index2]->x         = temp->x;
  378.    ref[index2]->y         = temp->y;
  379.    ref[index2]->color     = temp->color;
  380.    ref[index2]->index     = temp->index;
  381.  
  382. Tile *temp  = ref[index1];
  383.  
  384. ref[index1] = ref[index2];
  385. //ref[index1]->color = temp->color;
  386. ref[index2] = temp;
  387. */
  388.  
  389.  CopiarTile(ref, index1,index2);
  390.  
  391. }
  392.  
  393. int isCollide()
  394. {
  395.    for(unsigned int g=0; g < tile_set.size();g++)
  396.       {
  397.  if(check_collision( cursor_pos, tile_set[g]->getRect()))
  398.  {
  399.  cout <<"posicion "<< tile_set[g]->x<<" type "<<tile_set[g]->color<<endl;
  400.  return tile_set[g]->index;
  401.  }
  402.       }
  403. cout <<"-9999"<<endl;
  404. return -9999;
  405. }
  406.  
  407. void CopiarTile(vector<Tile*> &tile, int index1,int index2)
  408. {
  409. cout <<"preparando para copiar "<<endl;
  410.    cout <<"     x1 : " <<tile[index1]->x<<endl;
  411.    cout <<"     x1 : " <<tile[index1]->y<<endl;
  412.    cout <<"     x1 : " <<tile[index1]->color<<endl;
  413.    cout <<"     x1 : " <<tile[index1]->index<<endl;
  414.    cout <<"---------------------------------------------------------------------------------------\n";
  415.    cout <<"     x2 : " <<tile[index2]->x<<endl;
  416.    cout <<"     x2 : " <<tile[index2]->y<<endl;
  417.    cout <<"     x2 : " <<tile[index2]->color<<endl;
  418.    cout <<"     x2 : " <<tile[index2]->index<<endl;
  419.  
  420.  
  421. Tile *temp1 = tile[index2];
  422. Tile *temp2 = tile[index1];
  423.  
  424.  
  425. cout <<" copiar "<<endl;
  426.    cout <<"     x : " <<temp1->x<<endl;
  427.    cout <<"     y : " <<temp1->y<<endl;
  428.    cout <<" color : " <<temp1->color<<endl;
  429.    cout <<"----------------------------------------------------------------------------\n";
  430.    cout <<"copiar "<<endl;
  431.    cout <<"     x2 : " <<temp2->x<<endl;
  432.    cout <<"     y2 : " <<temp2->y<<endl;
  433.    cout <<" color2 : " <<temp2->color<<endl;
  434.    cout <<"----------------------------------------------------------------------------\n";
  435.    tile[index1]=temp1;
  436.    tile[index2]=temp2;
  437.  
  438. }
  439.  


hay esta too lo que he hecho :D espero que puedna ayudarme y esto lo ayude a ustedes tambien :D
« Última modificación: 21 Enero 2016, 17:27 pm por bash » En línea

gracias por responder mis dudas
ivancea96


Desconectado Desconectado

Mensajes: 3.412


ASMático


Ver Perfil WWW
Re: intercambiar valores dentro de un vector
« Respuesta #3 en: 21 Enero 2016, 17:31 pm »

Bueno, no sé qué pretendes hacer. Pero ten en cuenta que la función "copiar", más que copiar, intercambia :o
En línea

bash

Desconectado Desconectado

Mensajes: 258



Ver Perfil
Re: intercambiar valores dentro de un vector
« Respuesta #4 en: 21 Enero 2016, 19:13 pm »

realmente puse mal el identificador
pero si te fijas en esta linea

Código
  1.  
  2. Tile *temp1 = tile[index2];
  3. Tile *temp2 = tile[index1];
  4. ....
  5.          tile[index1]=temp1;
  6.          tile[index2]=temp2;
  7.  
  8.  


eso seria el intercambio aunque al final la aplicacion explota immediatamente uso el evento.

En línea

gracias por responder mis dudas
ivancea96


Desconectado Desconectado

Mensajes: 3.412


ASMático


Ver Perfil WWW
Re: intercambiar valores dentro de un vector
« Respuesta #5 en: 21 Enero 2016, 19:20 pm »

'explota' no ayuda a encontrar el error xD
Localiza la línea que tira el error. Para ello, si es necesario, coloca salidas por consola, cout, y así ver la línea exacta que lanza el error.
En línea

bash

Desconectado Desconectado

Mensajes: 258



Ver Perfil
Re: intercambiar valores dentro de un vector
« Respuesta #6 en: 21 Enero 2016, 23:16 pm »

deja de trabajar en la funcion CopiarTile(swapear)

la salida de cout es
Código
  1. -------------------------------------------------------------------
  2. posicion 416 type 0
  3. posicion 368 type 1
  4. CopiarTilepreparando para copiar
  5.     x1 : 80
  6.     x1 : 32
  7.     x1 : 0
  8.     x1 : 1
  9. ---------------------------------------------------------------------------------------
  10.     x2 : 80
  11.     x2 : 32
  12.     x2 : 0
  13.     x2 : 1
  14.  
  15. copiar
  16.     x : 80
  17.     y : 32
  18. color : 0
  19. ----------------------------------------------------------------------------
  20. copiar
  21.     x2 : 80
  22.     y2 : 32
  23. color2 : 0
  24. ----------------------------------------------------------------------------
  25.  
  26.  
  27.  
  28.  


pero hasta me doy cuenta que lo que hace es lo siguiente los elementos se copian pero como se copian todos los datos quedan igual. estoy pensando cambiar std::map o unordered_map ya que con ellos puedo usar clear() es mas facil copiar segun entiedo.
« Última modificación: 21 Enero 2016, 23:21 pm por bash » En línea

gracias por responder mis dudas
ivancea96


Desconectado Desconectado

Mensajes: 3.412


ASMático


Ver Perfil WWW
Re: intercambiar valores dentro de un vector
« Respuesta #7 en: 21 Enero 2016, 23:36 pm »

¿Qué error decías que te daba?
En línea

bash

Desconectado Desconectado

Mensajes: 258



Ver Perfil
Re: intercambiar valores dentro de un vector
« Respuesta #8 en: 21 Enero 2016, 23:46 pm »

se cerraba , pero no lo veo claro , ahora voy tener que apender a usar el GDB por que realmente nunca he depurado, voy a ver que sale en los trace y publico , y descubri que con std::map me hace lo mismo :D publicare en un par de horas voy a casa a ver si sigo alla ,escribo en un rato. gracias
En línea

gracias por responder mis dudas
Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines