Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

A small question about C++ vector std::rotate

+5 votes
asked Dec 2, 2021 by Areeb Sherjil (2,000 points)
edited Dec 2, 2021 by Areeb Sherjil

My aim is to make array2(actually a vector but named array2 for other reasons) equal to a rotated vector numerator.

The vector 'numerator' would normally look like this [0,5,6,8,....] but it needs to be rotated so the first non-zero term is first, so it should look like this [0,23,5,6,...] to [23,5,6.....]. The problem is that numerator vector cannot be changed(requirement), so I want to make a temporary vector named array2 equal to it.

code snippet:

size_t counter = finder(numerator); // finds the index of the first non-zero term
array2 = std::rotate(numerator.begin(), (numerator.begin() +counter), numerator.end());

This unfortunately gives an error :

Severity Code Description Project File Line Suppression State Detail Description

Error (active) E0349 no operator "=" matches these operands Polynomial Long Division operand types are: std::vector<double, std::allocator<double>> = std::_Vector_iterator<std::_Vector_val<std::conditional_t<true, std::_Simple_types<double>, std::_Vec_iter_types<double, size_t, ptrdiff_t, double *, const double *, double &, const double &>>>>

This error does not make any sense to me as I am not overloading operators, there is no object here and both vectors of type double.

1 Answer

+2 votes
answered Dec 3, 2021 by Peter Minarik (63,320 points)
selected Dec 4, 2021 by Areeb Sherjil
Best answer

It seems to me that your problem is that you haven't fully understood how to use std::rotate().

The function does an in-place rotation, that is, it changes the input array. It also does not return any value (void).

Your code correctly would be similar to this:

#include <algorithm>
#include <iostream>
#include <vector>

void PrintVector(const std::string & message, const std::vector<int> & vec)
    std::cout << message;
    for (std::vector<int>::const_iterator it = vec.cbegin(); it != vec.cend(); ++it)
        std::cout << ' ' << *it;
    std::cout << std::endl;

int main()
    std::vector<int> original { 0, 23, 5, 6 };
    std::vector<int> replica(original);
    std::rotate(replica.begin(), std::find_if(replica.begin(), replica.end(), [](int i) { return i != 0; }), replica.end());
    PrintVector("replica:", replica);
    PrintVector("original:", original);
    return 0;

I hope this helps and the lambda expression is not too confusing in the std::find_if() statement.

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.