Neha Ghosh
Neha Ghosh

Reputation: 11

Why can't I copy this one vector to another?

The compiler says the following error message for my reverse vector function at the line "extra = lines[i]. I want to copy one vector to another with the assignment operator.

|no match for 'operator=' (operand types are 'std::vectorstd::__cxx11::basic_string<char >' and '__gnu_cxx::__alloc_traitsstd::allocator<std::__cxx11::basic_string<char >, std::__cxx11::basic_string >::value_type' {aka 'std::__cxx11::basic_string'})

Code:

void reverse_vector(vector<string>& lines){
    vector<string> extra;
    int i;
    for(i = 0; i < lines.size(); i++){
        extra = lines[i];
        lines[i] = lines[lines.size() - 1 - i];
        lines[lines.size() - 1 - i] = extra;
        cout << lines[i] << " ";
        cout << endl;
    }
}

Upvotes: 0

Views: 61

Answers (1)

Bill Lynch
Bill Lynch

Reputation: 81916

Two issues:

  1. extra should have the type of lines[i]. So it should just be std::string extra.
  2. When you're implementing reverse like this, you only want to iterate half the length of the array.

And for readability:

  1. You should use std::swap() to swap things around. It's far easier to read.

So it would look like:

void reverse_vector(vector<string>& lines) {
    for(int i = 0; i < lines.size() / 2; i++) {
        string extra = lines[i];
        lines[i] = lines[lines.size() - 1 - i];
        lines[lines.size() - 1 - i] = extra;
    }
}
void reverse_vector(vector<string>& lines) {
    for(int i = 0; i < lines.size() / 2; i++)
        std::swap(lines[i],
                  lines[lines.size() - 1 - i]);
}

Upvotes: 2

Related Questions