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

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

本文关键字:改变 字符串 为什么 resize String 使用      更新时间:2023-10-16

我使用以下代码块想要使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();
}

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'
// ...