0

Having this:

#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;
    }
}

I am using this line:

vector<Info> &ret; 

without initialization. I know I can use pointer, where I do not have to initialize it, but I want to use reference. Is there a way to make default initialization for that vector or is my only option to use pointer?

milanHrabos
  • 2,010
  • 3
  • 11
  • 45
  • 1
    You need return by value or pass output parameter as argument by value. You can not use reference or pointer without initialization. – user7860670 Jul 07 '20 at 14:38

1 Answers1

0

The standard requires initialization of references, so no, the compiler will not let you leave it uninitialized. You are actually trying to use and return a reference to nothing, instead you should either work in-place on your function argument vec or create a local variable and return the value vector<Info> ret. Remember to change the return type to vector<Info>, returning a reference to a local variable results in undefined behaviour. You can rely on return value optimization.

malik
  • 66
  • 9