[] operator confusion

Im following c++ primer and they give and example of using the [] operator to im guessing assign to a string. This is the code they use:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
  #ifndef SCREEN_H
#define SCREEN_H

#include <string>

struct screen{
public:
    //type alais(scope within class)
    using pos = std::string::size_type;
    //constructors
    screen() = default;
    screen( pos &h, pos &w, std::string &cntnt) : height(h), width(w), content(cntnt){}
    screen(const pos& h, const pos& w, char c) : height(h), width(w), content(h*w,c){}
    //member function declares
    screen& set(char);
    screen& set(pos,pos,char);

    //private members
    private:
    pos cursor;
    pos height = 0, width = 0;
    std::string content = " ";
};

inline screen &screen::set(char c){
content[cursor] = c; // <--HERE
return *this; // return this object as an lvalue
}


inline screen &screen::set(pos r, pos col, char ch){
content[r*width + col] = ch; // <-- AND HERE
return *this; // return this object as an lvalue
}



#endif // SCREEN_H 


I think it is a way to use the string class constructor string(size_type,char) but they dont explain it at all and if I try to reproduce it outside the class like below the compiler doesnt complain but the program crashes. Can someone please explain to me what they are doing and why it does not work for me.

1
2
3
4
5
6
7
8
using pos = std::string::size_type;
pos test = 5;
char c = 'n';
string stest = " ";

stest[test] = c;

cout << stest;


It's being used to access a character in the string, the same way you access elements in an array.
http://www.cplusplus.com/reference/string/string/operator%5B%5D/

Your test program is crashing because you trying to access the sixth char in a string of length 1.
Last edited on
Cant believe I didnt understand that, I definitely knew about using the [] operator to denote a char in a string... Thanks!
I think it is a way to use the string class constructor string(size_type,char)

No, it's not a constructor. It's an operator that stores a character into the n'th position of the string.

Your second snippet crashed because your string was initialized to a single blank and you tried to store a character into the 6'th position which was beyond the limit of the string.
Last edited on
Topic archived. No new replies allowed.