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;
}
}
CodePudding user response:
Two issues:
extra
should have the type oflines[i]
. So it should just bestd::string extra
.- When you're implementing reverse like this, you only want to iterate half the length of the array.
And for readability:
- 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]);
}
CodePudding user response:
You can use the std::copy algorithm with reverse iterators:
void reverse_vector(const std::vector<std::string>& lines)
{
std::vector<std::string> extra;
std::copy(lines.rbegin(), lines.rend(), std::back_inserter(extra));
for(auto elem : extra) std::cout << elem << " ";
}