samedi 21 juillet 2018

Using operator[] of a std::vector, when variable is a pointer

I have trouble figuring out, how to accomplish this simple task:

  • create a std::vector
  • pass pointer/reference to a function sort(..)
  • function sort(..) changes the value of an index

What I currently have:

(const & variant)

void sort_one(int source_index, const std::vector<int> &source_list, const std::vector<int> &target_list)
{
    int p = 0;
    int v = source_list.at(source_index);

    for (int i =0; i < source_list.size(); ++i)
    {
        if (source_list.at(i) >= v)
            p++;
    }

    target_list[p] = v; # error: cannot assign to return value because function 'operator[]' returns a const value
}

(const * variant)

void sort_one(int source_index, const std::vector<int> *source_list, const std::vector<int> *target_list)
{
    int p = 0;
    int v = source_list->at(source_index);

    for (int i =0; i < source_list->size(); ++i)
    {
        if (source_list->at(i) >= v)
            p++;
    }

    (*target_list)[p] = v; # error: cannot assign return value because function 'operator[]' returns a const value
}

I tried changing the variations for some time, but so far I couldn't wrap my head around it. I'm also not sure what search terms to use, I didn't find anything useful.

Aucun commentaire:

Enregistrer un commentaire