c++ - 修复 std::vector<std::vector<UC>> lum 中调用 'assign' 时出现的错误:没有匹配函数;

标签 c++ vector

我有来自 C++ 的引用代码:

typedef unsigned char UC;
std::vector<std::vector<UC> > lum;
int h;
int w;

这行代码:

lum.assign(h,w);

我编译这段代码并得到错误: 没有匹配的成员函数来调用“分配”

如何修复这个错误?有没有与此功能匹配的功能可以替换?

最佳答案

该错误是正确的,因为这意味着您正在尝试分配 h h 值的金额(无论 w 的值是什么) .

但是,如assign要求分配的值是分配的类型的实例(又名 value_type ),那么您实际上需要将值分配为类型 vector<UC> .

与您的代码相比,您尝试为二维 vector 分配一个整数值,该整数值(如前所述)与 value_type 不匹配的lum ( vector<UC> ) - 这解释了您遇到的错误。 为什么?因为二维 vector 实际上是(某种类型) vector 的 vector 。因此,你只能将该类型的 vector 分配给二维 vector 没有别的

换句话说,类似这样的代码应该是正确的代码:

typedef unsigned char UC;
std::vector<std::vector<UC> > lum;
int h;
int w;

UC initial = 'C';

vector<UC> vec(w, initial);
lum.assign(h, vec);

但是,当您尝试填充二维 vector 时,我只能推测您正在尝试以某种任意方式分配或初始化 vector 。根据您想要做什么,这种方法可能不合适。

引用:

http://www.cplusplus.com/reference/vector/vector/assign/

关于c++ - 修复 std::vector<std::vector<UC>> lum 中调用 'assign' 时出现的错误:没有匹配函数;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21770132/

相关文章:

c++ - Operator= 从 QMatrix4x4 派生时不起作用

c++ - 有没有办法在 c++ 中禁用旧的 c 样式转换

c++ - Cmake 和 Qt5 链接错误

r - 如何从向量中获取每三个记录?

c++ - 用变量初始化 vector ,C++

c++ - 在 std::vector 中查找索引

c++ - 为什么 std::is_assignable 不适用于原始类型? (确认)

c++将模板与单例一起使用

c++ - 连接两个std::vector

c++ - 与 vector 迭代器一起使用时出现奇怪的输出