Exercise help on Arrays and Vectors

Why
std::to_string(student_scores.back());
does not work?
if std::vector student_scores;

How must I convert it to string?

@Sarvango Sorry, I don’t understand.
Is this related to the (already fixed) issue reported by Leonod33?

Why
std::to_string(student_scores.back());
does not work?
if std::vector student_scores;

Can you provide some context? Is this from the Making the Grade concept exercise?
Can you show your complete code and the error message (in fenced code blocks)?

Not related to fixed issue. But it’s in “Making the Grade”

code:

int i=student_scores.size();
std::vector<std::string> ranking{0};
 while(!student_scores.empty()){  
    ranking.begin()=std::to_string(i)+". "+student_names.back()+": "
        +std::to_string(student_scores.back());
    student_scores.pop_back(); 
    student_names.pop_back();
    i--;
}

Result:

error: no match for 'operator=' (operand types are 'std::vector<std::__cxx11::basic_string<char> >::iterator' and 'std::__cxx11::basic_string<char>')
   50 |             +std::to_string(student_scores.back());
ranking.begin()=std::to_string(i)+". "+student_names.back()+": "
        +std::to_string(student_scores.back());

I think this line is supposed to insert a new element at the beginning of ranking, right?
But ranking.begin() gives you an iterator, not something that you can assign a string to.

If you want to insert something into a std::vector, call .insert() (see cppreference.com).

But in general (slightly advanced topic!) it’s better to avoid an insertion at the beginning or somewhere in the middle of a contiguous container because all trailing elements have to be shifted to the right. Instead, append elements if you can (with .push_back()).

insert(i,*) and push_back() do not work too…
This exercise turned out as a nightmare for me.

code:

int i{0},k=student_scores.size();
std::vectorstd::string ranking{0};
for (i=0;i<k;i++) {
ranking.push_back()=std::to_string(i)+". “+student_names.at(i)+”: "
+std::to_string(student_scores.at(i));
}

result:

error: no matching function for call to 'std::vector<std::__cxx11::basic_string<char> >::push_back()'
   49 |     ranking.push_back()=std::to_string(i)+". "+student_names.at(i)+": "

Instead of assiging with

ranking.push_back() = some_string;  // incorrect

you need to pass the string as an argument to the function:

ranking.push_back(some_string);
1 Like

You seem to be jumping straight into coding without getting a feel for the language first. This is fine, I’m also into learning by doing. But you should have some documentation open to check things while you’re coding. Things like the interface of the classes, the headers, etc. One good reference for the C++ language is here