Sunset Wan
Sunset Wan

Reputation: 23

After using String.resize(), why doesn't the size of the string change?

I used the following block of my code to want to make the size of each element of tableOfReservedWords being 8 :

for(auto s : tableOfReservedWords) {
        s.resize(8);
        cout<< "S is " << s << " ,Size is "<< s.size() << endl;
   }

but when I run this c++ program, the result is :

S is VAR ,Size is 8
S is INTEGER ,Size is 8
S is BEGIN ,Size is 8
S is END ,Size is 8
S is WHILE ,Size is 8
S is IF ,Size is 8
S is THEN ,Size is 8
S is ELSE ,Size is 8
S is DO ,Size is 8
---------------------
S is VAR ,Size is 3
S is INTEGER ,Size is 7
S is BEGIN ,Size is 5
S is END ,Size is 3
S is WHILE ,Size is 5
S is IF ,Size is 2
S is THEN ,Size is 4
S is ELSE ,Size is 4
S is DO ,Size is 2

Now I am confused about this result. It's clear that I have used the public member function resize() but the usage didn't work when I called the function check(). Is there anyone who is proficient in C++ willing to help me? I'm just a complete novice. Thanks in advance.


Here is my entire code:

#include <iostream>
#include <vector>
#include "string"

using namespace std;

vector<string> tableOfReservedWords {"VAR", "INTEGER", "BEGIN", "END", "WHILE", "IF", "THEN", "ELSE", "DO"};

void check() {
    for(auto s : tableOfReservedWords) {
        //s.resize(8);
        cout<< "S is " << s << " ,Size is "<< s.size() << endl;
    }
}

int main(int argc, char *argv[]) {
    for(auto s : tableOfReservedWords) {
            s.resize(8);
            cout<< "S is " << s << " ,Size is "<< s.size() << endl;
  }

    cout<< "---------------------" << endl;
    check();
}

Upvotes: 1

Views: 791

Answers (1)

molbdnilo
molbdnilo

Reputation: 66371

Your loop in main is resizing copies of the strings:

for(auto s : tableOfReservedWords) 
    s.resize(8);  // Resizes 's', which is a copy of the original string

It works the same as

std::string word = "VAR";

void check()
{
    std::cout << word.size();
}

int main()
{
    std::string w = word;
    w.resize(8);
    check();
}

If you want to resize the strings in the vector, you need to use references to those strings instead:

for (auto& s : tableOfReservedWords) {
    s.resize(8);  // Resizes a vector element which we call 's'
    // ...

Upvotes: 4

Related Questions