拥有以下内容:
#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;
}
}我使用的是这一行:
vector<Info> &ret; 而不进行初始化。我知道我可以使用指针,在那里我不必初始化它,但我想使用引用。有没有办法对这个向量进行缺省初始化,或者我唯一的选择就是使用指针?
发布于 2020-07-07 22:41:53
该标准要求初始化引用,所以不,编译器不会让你不初始化它。您实际上正在尝试使用并返回一个对nothing的引用,相反,您应该就地处理您的函数参数vec,或者创建一个局部变量并返回值vector<Info> ret。请记住将返回类型更改为vector<Info>,返回对局部变量的引用会导致未定义的行为。你可以依靠返回值优化。
https://stackoverflow.com/questions/62777629
复制相似问题