C++:向量数组
C++: array of vectors
我有一个通过引用获得 5 个向量的操作:
void ReadFromFile(string nomFitxer, vector<int> &n, vector<int> &s, vector<int> &o, vector<int> &e, vector<int> &a){
我在动作中创建了一个向量数组,vector<int> ve[] = {n, s, o, e, a};
认为它们是相同的,但当然它们不是......因为阅读后我发现 ve[0] 大小为 5,n 大小为 0。
我怎样才能从给定的向量中制作一个向量数组?
提前谢谢你
#include <vector>
#include <iostream>
using std::vector;
void foo(vector<int> & a, vector<int> & b) {
vector<int> vectors[] = {a, b};
std::cout << "vectors[0].size() = " << vectors[0].size() << std::endl;
vectors[0][0] = 42;
std::cout << "vectors[0][0] = " << vectors[0][0] << std::endl;
}
int main() {
vector<int> one = {1, 2, 3, 4};
vector<int> two = {11, 12, 13, 14};
std::cout << "one[0] = " << one[0] << std::endl;
foo(one, two);
std::cout << "one[0] = " << one[0] << std::endl;
}
此代码创建一个向量数组,这些向量是从作为函数参数传递的引用的向量复制构造的。
因此,向量的修改不会逃脱函数范围......而且你有副本的缺点。
由于您使用的是vector<int> &
(非常量引用(,我假设您希望这些向量成为"输出"参数。引用数组是不可能的,但您可以使用std::reference_wrapper
来规避此限制:
#include <functional>
void bar(vector<int> & a, vector<int> & b) {
using vref = std::reference_wrapper<vector<int>>;
vref vectors[] = {a, b};
std::cout << "vectors[0].size() = " << vectors[0].get().size() << std::endl;
vectors[0].get()[0] = 42;
std::cout << "vectors[0][0] = " << vectors[0].get()[0] << std::endl;
}
// Now use bar instead of foo with the above main function!
我试着弄清楚
void foo(std::vector<int> &a, std::vector<int> &b)
{
std::vector<int> ve[] = {a, b};
std::cout << ve[0].size() << "/" << ve[1].size() << std::endl;
std::cout << a.size() << "/" << b.size() << std::endl;
}
int main()
{
std::vector<int> a = {0, 1, 2};
std::vector<int> b = {};
foo(a, b);
return 0;
}
此代码有效,输出为:
3/0
3/0
因此,这可能是向量初始化的错误。
相关文章:
- 将数组/向量发送到 c++ 脚本的 cython 示例
- C++:在多个线程中访问同一数组/向量的不同单元格是否会产生数据竞赛?
- 将指向多维数组向量中的单个项的指针传递给函数 c++
- 数组向量的文件 I/O
- 在一行中初始化和引入数组向量的正确方法?
- C++ 返回具有最小硬币的数组/向量以获得价值动态规划
- 将整数向量转换为字节数组向量,然后调用每个字节数组
- 我可以在不循环访问数组/向量的情况下检查数组/向量中的单词吗?
- (C )创建可以从功能访问的动态全局数组/向量
- 提升是否具有用于数组向量的智能指针
- 将函数应用于数组向量的元素
- 数组向量的内存布局是什么
- 获取数组/向量末尾地址的未定义行为
- "Empty"数组\向量成员 C++
- 将字符串向量转换为双2-D数组向量
- 排序多维数组/向量
- 如何创建模板化对象的数组/向量
- 如何在数组向量上使用 std::find
- 无法删除C++中的数组/向量
- 具有元素自定义构造函数的对象数组/向量