Can I convert std::vector<std::pair<int, int>> to an array in C++?

Asked 2 years ago, Updated 2 years ago, 140 views

As the title says, I want to save vector with pair value as an array, is it possible?

c++ stl vector

2022-09-21 21:19

1 Answers

If you convert the first and second of the pair to unsigned char[2], you can write it like this.

#include <iostream>
#include <vector>

unsigned char** convert(std::vector<std::pair<int,int>> vector_pair){
  int n = vector_pair.size();
  unsigned char** ret = new unsigned char*[n];


  for(int i=0; i < n ;i++){
    ret[i] = new unsigned char[2];
    ret[i][0] = (unsigned char)vector_pair[i].first;
    ret[i][1] = (unsigned char)vector_pair[i].second;
  } 

  return ret;
}


int main()
{
  std::vector<std::pair<int,int>> vector_pair
  {
    {1, 2},
    {3, 4},
    {5, 6}
  };  
  unsigned char** converted = convert(vector_pair);
}


2022-09-21 21:19

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.