Reputation: 91
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. P.s. everything has to be dynamic because I will import data from a file Please help :)
Upvotes: 2
Views: 526
Reputation: 3818
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)
Upvotes: 3
Reputation: 122133
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?).
Upvotes: 2