c++ 向量的值逆序输出_如何使用C++中的循环将字符串指针值赋给向量的元素

浏览OP的代码并尝试解释发生了什么:

int main()

{

string word = word; // this creates a string named word and sets word

// to itself. In other words, other than creating

// word, it doesn't do anything.

// most likely the intent was

// string word = "word";

// The "" marks contained text as data to be

// Interpreted as a string

string word1; // these create more words set to the default

string word2; // empty string that don't do much for reasons explained

string word3; // below

string word4;

string word5;

string *pointer = &word; // this is good

string words[5] = { word1, word2, word3, word4, word5 };

// this created an array of 5 strings and copied the values of word1

// through word5 into array elements 0 through 4. Since word1 through 5

// contain the default value, this does nothing more than

// string words[5];

for (int i = 0; i <= 5; i++) // words contains 5 slots, 0 though 4.

// the loop conditions cover 0 through 5

// it will compile but will have undefined

// behaviour (maybe crash, maybe not)

// when words[5] is reached.

// Very likely the intent was

// for (int i = 0; i < 5; i++)

{

word[i] = *pointer; // this is most likely a typo.

// The odd message about assigning a string to

// a character is because you can use [] to

// access individual characters in a string

// just like you can an array

// words[i] = *pointer;

// is probably what was intended

cout << word[i] << endl; // this is good, but probably not what is

// intended. It will print out the

// characters in word one by one.

// as with above, it likely should be

// cout << words[i] << endl;

}

return 0;

}更正并删除了箔条我们得到

int main1()

{

string word = "word";

string *pointer = &word;

string words[5];

for (int i = 0; i < 5; i++)

{

words[i] = *pointer;

cout << words[i] << endl;

}

return 0;

}一种稍微安全的方法。我们可以通过将单词数组的总大小除以单个元素的大小来将循环绑定到单词中的字符串数。这样它就永远不会超出范围。注意我已经将i的类型从有符号的int更改为size_t,这是一个非常适合用作索引的无符号值。

int main2()

{

string word = "word";

string *pointer = &word;

string words[5];

for (size_t i = 0; i < sizeof(words)/sizeof(words[0]); i++)

{

words[i] = *pointer;

cout << words[i] << endl;

}

return 0;

}或者我们可以使用C++ 11中的增强型for循环

int main3()

{

string word = "word";

string *pointer = &word;

string words[5];

for (string & wordref: words) // note the &. In this case we are using a reference,

// a restricted pointer, to the strings in words.

// We need the reference or a pointer because

// otherwise we will be given a copy of the string

// in words, and the assignment will be to the copy,

// not to the source string in words.

{

wordref = *pointer;

cout << wordref << endl;

}

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值