spx31
spx31

Reputation: 133

Pointers: Expression not assignable in c++

#include <iostream>
#include <vector>

using namespace std;

template<typename T>
void new_insertion_sort(std::vector<T> &v)
{
    for(auto iter = v.begin(); iter != v.end(); ++iter)
    {
        auto j = iter;
        std::cout << "1 ";
        while(j > v.begin())
        {
            if(*j > *j-1) // we do not want iterator here, but the value at that
                {break;}

            auto current = *j-1; // save for swap
            *j-1 = *j; // swap
            *j = current; // restore position before, without it the two adjacent would be the same

            j--;

        }



    }

}


void insertion_sort(std::vector<double> &v)
{
    for(int i = 0; i < v.size(); i++)
    {
        int j = i;

        while(j > 0)
        {
            if(v[j] > v[j-1])
                {break;}

            double current = v[j-1]; // save for swap
            v[j-1] = v[j]; // swap
            v[j] = current; // restore position before, without it the two adjacent would be the same

            j--;

        }



    }

}

template<typename T>
void print_vector(T v){

    for(auto &element: v)
    {
        std::cout << element << std::endl;
    }

}

int main(int argc, char const *argv[])
{
    std::vector<double> v={5,4,3,2,7};
    std::vector<int> w={4,6,23,6,35,235,346,37,46};

    std::cout << " Dies ist der geordnete Vektor! " << std:: endl;
    insertion_sort(v);
    print_vector(v);




    new_insertion_sort(v);
    new_insertion_sort(w);
    std::cout << " Dies ist der geordnete Vektor v ! " << std:: endl;
    print_vector(v);
    std::cout << " Dies ist der geordnete Vektor v ! " << std:: endl;
    print_vector(w);

    return 0;
}

In the first function new_insertion_sort I am trying to write an insertion sort function for generic types. The error comes from the lines, where I try to "swap". It is supposed to take the value in the vector where the iterator currently is ( for example at Index 2 I wanna get the value ) and assign it to the other position.

The error is: insertion.cpp:19:9: error: expression is not assignable *j-1 = *j; // swap

I'm pretty sure my confusion stems from my poor understanding of pointers, so any tips are appreciated

At first I tried it with v[j-1]= v[j] etc. so using the iterators directly in the braces, but that did not work either.

Upvotes: 0

Views: 2325

Answers (1)

Edward Strange
Edward Strange

Reputation: 40859

You have a precidence error.

*(j-1) = *j;

That fixes it.

Upvotes: 2

Related Questions