将vector初始化为0
Initialize vector to zero
初始向量"perm"为空。我想根据循环的索引把它设为0。但我遇到错误"矢量下标超出范围",而做下面的代码。
我把"perm(charLength, 0)"放在任何循环之外的"Start()"方法中,这样它就不会被重置,它用于累积值。
DecodeEngine.h
class DecodeEngine
{
public:
vector<int> temp;
vector<int> perm;
//Default constructor
DecodeEngine();
//Declare a virtual destructor:
virtual ~DecodeEngine();
//Methods
string GetFilePath();
Mat Start();
void FrameTo8by8();
};
DecodeEngine.cpp
Mat DecodeEngine::Start()
{
charLength = 160;
//Initialize perm to zero
perm(charLength, 0);
//Loop 1st 100 frame of header
while(true)
{
if(frame_count <= 100)
{
FrameTo8by8(); //Proccess and algorithm
namedWindow("dctBlockImage");
imshow("dctBlockImage", dctImage); //display watermarked image
if(waitKey(30) == 27) //wait for 'esc' key press for 30 ms. If 'esc' key is pressed, break loop
{
cout << "esc key is pressed by user" << endl;
break;
}
frame_count++;
}
else
{
cout << endl;
cout << "End of video" << endl;
cout << endl;
destroyWindow("Original Video");
destroyWindow("dctBlockImage");
break;
}
}
void DecodeEngine::FrameTo8by8()
{
for(int i = 0; i < height-16; i += 16)
{
for(int j = 0 ; j < width-16; j += 16)
{
if(j > 112)
{
if(((sum4 / 4) - avg) > 0)
{
value = 0;
temp.push_back(value);
}
else
{
value = 1;
temp.push_back(value);
}
}
if(temp.size() == charLength)
{
for(int a = 0; a <= temp.size(); a ++)
{
//Initialize perm to zero
perm[a] = 0;
if(temp[a] == 1)
{
perm[a]++;
}
//Reset temp for next frame to use
temp[a] = 0;
}
}
}
}
}
这一行:
perm(charLength, 0);
不调用构造函数std::vector(size_t, const T&)
并初始化值为10
的160个元素的向量。事实上,我根本看不出这是如何编译的,因为vector类没有operator()
。
std::vector
包含一个成员函数assign()
,您可以替换它:
perm.assign(charLength, 0);
在下面这段代码中,您超出了范围:
...
if(temp.size() == charLength) // ok! temp.size() is same as perm.size()
{
for(int a = 0; a <= temp.size(); a ++) // !!! loop will execute with a=temp.size() and stop afterwards
{
//Initialize perm to zero
perm[a] = 0; // !!! but subscripts start with 0 and go to temp.size()-1
相关文章:
- 在main()之外初始化std::vector会导致性能下降(多线程)
- 为什么std::vector和std::valarray初始化构造函数不同
- 初始化 std::vector 替换为单大括号而不是双大括号
- 使用大括号初始化 std::vector 使用初始值设定项列表
- 为什么初始化 std::vector 时不能使用模板整数?
- 我可以列表初始化 std::vector 并完美转发元素吗?
- 分别声明和初始化 vector<vector<int>>
- 如何使用字符串文字优雅地初始化 vector<char *>?
- 如何初始化Vector
- 是否可以用map中的键初始化vector ?
- 初始化vector时出错
- 在c++中初始化vector类成员
- 在结构体中初始化vector
- 初始化vector常量数组
- 如何在类模板的构造函数中初始化vector成员变量
- 使用重复push_back()初始化vector时的问题
- 在struct vector中初始化vector
- 初始化Vector迭代器
- 没有匹配的构造函数,用于使用 CLANG++ 3.2 初始化'vector<string>'
- 初始化vector类型的静态类成员