错误“返回”是什么意思:在C ++中不能从“ std :: _ Vb_reference <std :: _ Wrap_alloc <std :: allocator <std :: _ Vbase >>>”转换为“ T&”?

如何解决错误“返回”是什么意思:在C ++中不能从“ std :: _ Vb_reference <std :: _ Wrap_alloc <std :: allocator <std :: _ Vbase >>>”转换为“ T&”?

我对编程非常陌生,要了解我正在使用Bjarne Stroustrup的《使用C ++编程,原理和实践》 ,第二版。在前几章中,作者提供了一个供学生使用的头文件,称为“ std_lib_facilities.h”(link)。

在解决其中一个练习中,我编写了一个(对于我的标准而言)是一个非常复杂的程序,其中包含一些使用头文件中的功能的功能。

#include "../../../std_lib_facilities.h"

bool vector_has_distinct_values(vector<short> v) //checks if the passed vector has distinct values
//no pre- or postconditions necessary for this function because it makes no assumptions about its input (other than that
//it is composed of a vector of type short int,which the caller anyway checks),and it can only output true or false
//(both reasonable values)
{
    sort(v);
    for (int x = 0; x < v.size(); ++x)
    {
        if (x > 0 && v[x] == v[x - 1])
            return false;
    }
    return true;
}

int how_many_bulls_and_cows(vector<short int> answers,vector<short int> guesses)
//we assume that both vectors contain values >= 1 and <= 9,and that they have distinct values
//nb: in the answer generation function,we already checked that the answers vector has distinct values,so it's ok not to check it here
{
    int bulls = 0,cows = 0;
    if (!vector_has_distinct_values(guesses)) //check a pre-condition
        throw invalid_argument("Your guesses should be different numbers.");  //for distinct error handling by the caller
    for (int i = 0; i < answers.size(); ++i)
    {
        if (answers[i] < 0 || answers[i] > 9)                                 //more pre-condition checks
            throw runtime_error("bad answer generation (OOB values)");
        if (guesses[i] < 0 || guesses[i] > 9)
            throw runtime_error("the numbers must be single-digit,positive integers");
        for (int j = 0; j < guesses.size(); ++j)
        {
            if (guesses[j] == answers[i] && i == j)
                bulls++;
            else if (guesses[j] == answers[i])
                cows++;
        }
    }
    if (bulls < 0 || bulls > 4 || cows < 0 || cows > 4) //we are checking the post condition that -1 < bulls < 5 and -1 < cows < 5
        throw runtime_error("unexpected number of bulls and/or cows"); 
    return bulls * 10 + cows;
}

vector<short> generate_answers(vector<short> answers)
//we assume that answers is empty
{
    if (answers.size() > 0)
        throw runtime_error("the answers vector should be empty before answer generation");
    vector<bool> has_this_number_been_generated(10);
    short aux;
    for (int i = 0; i < 4; ++i)
    {
        while (true) {
            aux = randint(10);
            if (!has_this_number_been_generated[aux])
            {
                answers.push_back(aux);
                has_this_number_been_generated[aux] = true;
                break;
            }
        }
    }
    if (!vector_has_distinct_values(answers))
        throw runtime_error("bad answer generation (repeating values)");
    return answers;
}

int main()
{
    vector<short> answers(4);
    vector<short> guesses(4);
    int bulls,cows;
    int counter = 0;
    bool first_time = true;
    while (true)
    {
        if (first_time)
        {
            cout << "Welcome to bulls and cows!\n";
        }
        if (counter == 0)
        {
            answers = generate_answers(answers);
        }
        cout << "What are your guesses? ";
        try {
            for (int i = 0; i < guesses.size(); ++i)
            {
                cin >> guesses[i];
                if (!cin)
                    throw runtime_error("guesses should be positive,distinct,single-digit integers");
            }
            ++counter;
            int b_and_c = how_many_bulls_and_cows(answers,guesses); // this variable avoids unnecessary calls to this function
            bulls = b_and_c / 10;
            cows = b_and_c % 10;
        }
        catch(runtime_error& e) {
            cerr << "error: " << e.what() << '\n';
            return 1;
        }
        catch (invalid_argument& e) {                           
            cerr << "tip: " << e.what() << ". Try again!\n";  
            continue;
        }
        if (bulls == 4)
        {
            cout << "Congratulations,4 bulls! You win after " << counter << " guesses!\n";
            first_time = false;
            char answer = 0;
            cout << "Play again? ('y' or 'n')";
            try {
                cin >> answer;
                if (!cin)
                    throw runtime_error("invalid answer (answer must be a *character* among 'y' or 'n'");
                if (answer == 'y')
                {
                    counter = 0;
                    continue;
                }
                else if (answer == 'n')
                    break;
                else
                    throw runtime_error("invalid answer (answer should be 'y' or 'n')");
            }
            catch (runtime_error& e) {
                cerr << "error: " << e.what() << '\n';
                cout << "Goodbye!\n";
                return 1;
            }
        }
        cout << bulls << " bull(s) and " << cows << " cow(s)\n";
    }
    cout << "Goodbye!\n";
    return 0;
}

从本质上讲,它是游戏Bulls and Cows的一种实现,试图捕获所有可能的错误(在错误管理一章中)。

不幸的是,此代码无法编译,给了我以下错误: 'return': cannot convert from 'std::_Vb_reference<std::_Wrap_alloc<std::allocator<std::_Vbase>>>' to 'T &'

,该错误引用了“ std_lib_facilities.h”中的第95行。

作为一个初学者,这种语言对我来说是非常隐秘的,我不明白这意味着,或者如何解决此错误。我敢肯定这不是头文件的问题(可能是我的程序以意外/错误的方式与之交互),但这无助于我修复它,我也不明白。

当然,我欢迎对我的代码提出任何批评,因为这对我来说是非常宝贵的学习经验。有人可以向我解释这个问题吗?

编辑:这是产生错误的部分:

#ifdef _MSC_VER
    // microsoft doesn't yet support C++11 inheriting constructors
    Vector() { }
    explicit Vector(size_type n) :std::vector<T>(n) {}
    Vector(size_type n,const T& v) :std::vector<T>(n,v) {}
    template <class I>
    Vector(I first,I last) : std::vector<T>(first,last) {}
    Vector(initializer_list<T> list) : std::vector<T>(list) {}
#else
    using std::vector<T>::vector;   // inheriting constructor
#endif

    T& operator[](unsigned int i) // rather than return at(i);
    {
        if (i<0||this->size()<=i) throw Range_error(i);
        return std::vector<T>::operator[](i);
    }
    const T& operator[](unsigned int i) const
    {
        if (i<0||this->size()<=i) throw Range_error(i);
        return std::vector<T>::operator[](i);
    }
};

产生错误的特定行是第一个return std::vector<T>::operator[](i);

解决方法

您很不幸地发现vector<bool>的行为与其他vector的行为不同。 vector<bool>专门用于节省空间,并将其所有bool转换为位并将这些位打包为小整数数组。通常,您至少可以节省8:1的空间。

但这是有代价的。例如,当您使用[]时,不会像其他bool那样引用存储在vector中的vector,因为这是不可能的要引用一点,您将获得一个代表bool的临时代理对象。然后,由于无法引用该代理对象,因此会造成严重破坏。

特别是发生问题的地方是我们发现的std_lib_facilities.h中埋藏的vector包装器中

T& operator[](unsigned int i) // rather than return at(i);
{
    if (i<0 || this->size() <= i) throw Range_error(i);
    return std::vector<T>::operator[](i);
}

尝试通过引用返回代理。编译器立即对此付诸行动,因为代理将超出范围并在任何人可能使用它之前变为无效。用正确的语言来说,代理是一个右值,您不能引用一个右值。

有多种解决方案,但是大多数解决方案都不使用vector<bool>来完成此任务。典型的候选者使用vector<uint8_t>(或任何其他整数类型的vector),std::set<int>std:unordered_set<int>以允许快速查找以查看{{1 }}值已经在集合中(对于大型列表或稀疏列表,其速度可能比int快得多),但是由于我们知道可能值的范围,因此该范围很小,而且我认为{ {1}}最适合这份工作。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-