简体   繁体   中英

C++ Multidimensional Vector

how can I make a table like this with vector in C++:

65  A
66  B
67  C

I did it with a dynamic 2d array like this:

int** ary = new int*[2];
for (int i = 0; i < size; ++i)
    ary[i] = new int[size];

// fill the array
for (int i = 0; i < size; i++) {
    ary[i][0] = ascii_values[i];

}
for (int i = 0; i < size; i++) {
    ary[i][1] = ascii_chars[i];

}

How can I do this with vector? I was thinking of putting two vectors inside a third vector but I don`t know if that is possible. Ps everything has to be dynamic because I will import data from a file Please help :)

Your data is actually not really multidimensional, but rather a list of int, char pairs. Thus the most natural would be a std::vector<std::pair<int,char>> . Imho whenever you can name a pair, you should do so, ie that would be

struct Foo {    // I cannot, but you can choose better names
     int x;
     char y;
};

And create a vector via

std::vector<Foo> f;

For how to use a vector I refer you to the massive amount of material that you can find online.

If however, you already have your data in two vectors, as you mentioned in a comment, then the easiest is probably to use some

struct Bar {
    std::vector<char> x;
    std::vector<int> y;
};

which may contain the same data, but depending on how you need to process the data it might be more or less efficient compared to the std::vector<Foo> (do you need to access the chars and ints independently or always as those pairs?).

You can easily implement the behaviour above using a vector of std::pair . See the demo :

#include <utility>
#include <vector>
#include <algorithm>
#include <iostream>

int main() {
 std::vector<std::pair<int,char>> result;
 std::vector<int> ascii_vals {65, 66, 67};
 std::vector<char> ascii_chars {'a', 'b', 'c'};

 auto ItA = ascii_vals.begin();
 auto ItB = ascii_chars.begin();

 while(ItA != ascii_vals.end() && ItB != ascii_chars.end())
 {
    result.push_back(std::make_pair(*ItA,*ItB));

    if(ItA != ascii_vals.end())
    {
        ++ItA;
    }
    if(ItB != ascii_chars.end())
    {
        ++ItB;
    }
 }

 for(std::vector<std::pair<int, char> >::iterator it = result.begin(); it != result.end(); it++)
    std::cout << "(" << it->first << ", " << it->second << ")" << std::endl;

 return 0;
}

The code above will print:

(65, a)
(66, b)
(67, c)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM