简体   繁体   English

C ++多维向量

[英]C++ Multidimensional Vector

how can I make a table like this with vector in C++: 如何在C ++中使用vector制作这样的表:

65  A
66  B
67  C

I did it with a dynamic 2d array like this: 我是用这样的动态2D数组完成的:

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? 我该如何使用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 :) PS一切都必须是动态的,因为我将从文件中导入数据,请帮助:)

Your data is actually not really multidimensional, but rather a list of int, char pairs. 您的数据实际上并不是真正的多维数据,而是int, char对的列表。 Thus the most natural would be a std::vector<std::pair<int,char>> . 因此,最自然的将是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?). 其中可能包含相同的数据,但是取决于您需要如何处理数据,与std::vector<Foo>相比,效率可能更高或更低(您是否需要独立或始终以成对的方式访问char和int ?)。

You can easily implement the behaviour above using a vector of std::pair . 您可以使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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