gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:19:56 25 4
gpt4 key购买 nike

我使用以下代码块来使 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

现在我对这个结果感到困惑。很明显,我使用了公共(public)成员函数 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();
}

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

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

关于c++ - 使用String.resize()后,为什么字符串的大小没有变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50229412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com