I'm new to programming and I'm trying to code a function that gets the shortest string from a list, but everytime I run it, visual studio shows an error "Exception thrown: read access violation". Where is the mistake?
#include <iostream>
#include <string>
using namespace std;
const string &shortest_string(initializer_list<string> strings) {
string *shortest_one = nullptr;
for (string string : strings) {
if (shortest_one == nullptr) shortest_one = &string;
else {
if (string.size() < shortest_one->size()) shortest_one = &string;
}
}
return *shortest_one;
}
int main() {
cout << shortest_string({ "hello" , "my", "name", "is", "dan" }) << endl;
return 0;
}
You made variable with name that matches type name (string variable, string type?). Plus there is issue that you return pointer to object with local scope of life. That is UB. Using iterators your function would work like this: