Help with simple error

Hello all, I'm a beginner to C++ and having trouble with an assignment. I keep getting the error "Expression must be a modifiable lvalue". The program I'm writing is a simple letter frequency counter, where the user inputs a file and the program counts and stores the occurrences of each letter. I know how I would go about this using a fixed size array but the requirements for the prog is that I must use a dynamic array template which functions like a vector (which i have already created) with the typename of a struct containing the data.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct letters
{
    char letter;
    unsigned freq;
}


class letter_frequency
{
  ......
 

  dynamicArray <letters> P;
}


Whenever i try to assign something like say P[0].letters = 'a';
I get the error, any help would greatly be appreciated, thanks!
You have to assign inside a function.
Peter do you mean inside functions of the letter_frequency class?
I've tried doing it inside the constructor but it doesn't work.

LetterFrequencies::LetterFrequencies()
{
P.resize(26);
P[0].letter = 'a';
P[0].freq = 0;
......
}
As i know char can't assign with = because it is a constant string
Hmm i'm not sure but i get the same problem when i try to assign a 0 to the frequency.
What is dynamicArray?
dynamicArray is basically a class that functions much like a vector. It stores an allocated array of items.
Here is my header file for it, i can post the implementation too but it is quite long. Name is darray.

#include <iostream>

template <typename T> class darray;
template <typename T> std::ostream& operator << (std::ostream, const darray<T>&);

template <typename T>
class darray
{
public:

// Constructors
darray();
darray(const darray<T>&);
explicit darray(unsigned);
~darray();

// Constant members
unsigned size()const;
unsigned capacity() const;
const T& operator [](unsigned);
const T* find(const T&) const;

// Modification members
T& operator [](unsigned);
void pop_back();
void push_back(const T&);
void resize(unsigned);
void reserve(unsigned);

// Operators
darray& operator =(const darray&);
void operator +=(const darray&);
darray& operator +(const darray&)const;
bool operator ==(const darray&)const;

//Friends
friend std::ostream& operator << <T> (std::ostream&, const darray<T>&);

private:
T* arr;
unsigned used, cap;
};

#include "darray.cpp"
#endif
You have two operator[] with the only difference being the return type.

I thought this would not compile but I guess your compiler picks the version that returns a const reference and that's probably why you can't assign to it.

To fix this problem you should mark the const version as const.
 
const T& operator [](unsigned) const;

Last edited on
Oh my god, that worked. Cant believe i missed that. Thanks so much for the help peter.
Topic archived. No new replies allowed.