首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >什么是(或如何制作) cpp中向量的默认初始值设定项?

什么是(或如何制作) cpp中向量的默认初始值设定项?
EN

Stack Overflow用户
提问于 2020-07-07 22:32:05
回答 1查看 46关注 0票数 0

拥有以下内容:

代码语言:javascript
复制
#include <iostream>
#include <vector>
#include <string>

using namespace std;

struct Info{
    string word;
    unsigned int i;
};

vector<Info> &orig(vector<Info> &vec){
    vector<Info> &ret; //reference needs to be initialized, pointer does not have to
    size_t len = vec.size();

    for(int i=0; i<len; i++){
       int j = 0; 
        for(; j<len; j++){
            if(vec[i].word == vec[j].word){
                vec[i].i++;
                break;
            }
        }
        if(j=len){
            Info info{vec[i].word, 0};
            ret.push_back(info);
        }
    }
    return ret;
}

int main(){
    vector<Info> words, origs;
    string tmp;

    while(cin >> tmp){
        Info info{tmp, 0};
        words.push_back(info);
    }

    origs=orig(words);

    cout << "number of elements of vector: " << words.size() << ", of which are unique: ";
    for(int i=0; i<origs.size(); i++){
        cout << origs[i].word << endl;
    }
}

我使用的是这一行:

代码语言:javascript
复制
vector<Info> &ret; 

而不进行初始化。我知道我可以使用指针,在那里我不必初始化它,但我想使用引用。有没有办法对这个向量进行缺省初始化,或者我唯一的选择就是使用指针?

EN

回答 1

Stack Overflow用户

发布于 2020-07-07 22:41:53

该标准要求初始化引用,所以不,编译器不会让你不初始化它。您实际上正在尝试使用并返回一个对nothing的引用,相反,您应该就地处理您的函数参数vec,或者创建一个局部变量并返回值vector<Info> ret。请记住将返回类型更改为vector<Info>,返回对局部变量的引用会导致未定义的行为。你可以依靠返回值优化。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62777629

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档