首页 > 解决方案 > 为什么我的代码给出未声明的变量错误?

问题描述

   include "stdafx.h"
#include <vector>
#include <iostream>



    std::vector<int> biggest;

std::vector<int>vector1;
std::vector<int>vector2;


int main(){
biggest = [vector2[0],0]; //wrong initialization
for (int apply = 0; apply < (vector2.size()); apply++) {
    if (biggest[0] < vector2[apply + 1]) {
        biggest[0] = vector2[apply + 1];
        biggest[1] = apply + 1;
    }

}

错误 C2065“应用”:未声明的标识符。为什么会发生此错误,因为我已经在 for 循环中定义了应用变量。错误应该在最大(向量)的初始化中。为什么错误的编译器代码?即使是智能感知也没有给我错误是视觉工作室的错误吗?

标签: c++

解决方案


applyfor循环体的范围内,所以请放心,错误不存在。但是您知道循环体之后apply超出了范围吗?

我只是回答这个问题,因为您使用

vector2.size() - 1

如果vector2是空的,会给你带来地狱unsigned,因为上面的值会变大,你的程序会严重失败!利用

for (int apply=0; apply + 1 < vector2.size(); apply++) {

反而。


推荐阅读