使用String.resize()后,为什么字符串的大小不会改变?

问题描述 投票:1回答:1

我使用以下代码块来使tableOfReservedWords的每个元素的大小为8

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

但是当我运行这个c ++程序时,结果是:

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

现在我对这个结果很困惑。很明显,我使用了公共成员函数resize()但是当我调用函数check()时,用法不起作用。有没有精通C ++的人愿意帮助我?我只是一个完整的新手。提前致谢。


这是我的整个代码:

#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();
}
c++ string resize
1个回答
3
投票

你在main中的循环正在调整字符串的副本:

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

它的工作原理与之相同

std::string word = "VAR";

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

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

如果要调整向量中的字符串大小,则需要使用对这些字符串的引用:

for (auto& s : tableOfReservedWords) {
    s.resize(8);  // Resizes a vector element which we call 's'
    // ...
© www.soinside.com 2019 - 2024. All rights reserved.