I have created a string vector and want to fill it with a "range-based for loop" but it doesn't work. What am I doing wrong?
invalid initialization of reference of type ‘int&’ from expression of type ‘std::__cxx11::basic_string<char>’
Does the compiler not understand that I want to refer to a vector element, not a string?
When I used the classic "for loop" it worked correctly (I could access the desired element of the vector and write the value there), but I don't understand why it doesn't work with a range based for loop. My piece of code:
#include <iostream>
#include <vector>
typedef std::vector<std::string> massive;
using std::cin, std::cout, std::endl;
int main() {
int N = 0, M = 0;
std::string s_n = "";
cin >> N;
massive seats(N);
for (int& i: seats) {
cin >> s_n;
seats[i] = s_n;
}
return 0;
}
CodePudding user response:
Replace the loop with
for (std::string& s : seats) {
cin >> s;
}
In short, here s
is a reference that runs over seats
elements.