字符串的C++向量,为什么赋值结果相同的char引用?

Fac*_*doJ 1 c++ string pointers vector char

我目前正在学习C++,我想手动将值输入到字符串向量中,在存储之前处理每个字符.这是我使用的代码:

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

using namespace std;

int main()
{
    int i, height = 5, width = 5;
    vector<string> lab;
    lab.resize(height, "");
    string s;

    //For input reference
    cout << endl << "Input data:" << endl << "01234" << endl;

    //Input values
    for (i = 0; i < height; i++)
    {
        getline (cin, s);

        for (int j = 0; j < width; j++) 
        {   
            //Process char [...]
            lab[i][j] = s.at(j);
        }
    }

    //Show Matrix
    cout << endl << endl;
    for (int i = 0; i < height; i++)
    {   
        for (int j = 0; j < width; j++)
        {
            cout << lab[i][j] << " "; 
        }
        cout << endl;
    }

    //Show Addresses
    cout << endl << endl;
    for (int i = 0; i < height; i++)
    {   
        cout << "String Addr: " << (void*) &lab[i] << " | Chars Addr: ";
        for (int j = 0; j < width; j++)
        {
            //cout << lab[i][j] << " "; 
            cout << (void*) &lab[i][j] << " ";
        }
        cout << endl;
    }

    cout << endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

问题是字符串中的字符具有相同的地址(我不知道为什么).以下是程序执行的一个示例:

Input data:
01234
aaaaa
bbbbb
ccccc
ddddd
abcde

a b c d e 
a b c d e 
a b c d e 
a b c d e 
a b c d e 

String Addr: 0x8fe8008 | Chars Addr: 0xb773260c 0xb773260d 0xb773260e 0xb773260f 0xb7732610 
String Addr: 0x8fe800c | Chars Addr: 0xb773260c 0xb773260d 0xb773260e 0xb773260f 0xb7732610 
String Addr: 0x8fe8010 | Chars Addr: 0xb773260c 0xb773260d 0xb773260e 0xb773260f 0xb7732610 
String Addr: 0x8fe8014 | Chars Addr: 0xb773260c 0xb773260d 0xb773260e 0xb773260f 0xb7732610 
String Addr: 0x8fe8018 | Chars Addr: 0xb773260c 0xb773260d 0xb773260e 0xb773260f 0xb7732610
Run Code Online (Sandbox Code Playgroud)

最后你可以看到字符的地址是相同的,而字符串的地址是不同的.示例中的最终矩阵应该是:

a a a a a
b b b b b
c c c c c
d d d d d
a b c d e
Run Code Online (Sandbox Code Playgroud)

但相反,它是:

a b c d e 
a b c d e 
a b c d e 
a b c d e 
a b c d e 
Run Code Online (Sandbox Code Playgroud)

虽然我已经解决了这个问题,但是使用+=运算符而不是分配使用[],我仍然不知道上面的代码究竟是什么.为什么字符具有相同的引用?

Jay*_*Jay 5

你的作业越界越界:

lab[i][j] = s.at(j);
Run Code Online (Sandbox Code Playgroud)

lab[i]是有效的但是lab[i][j]对于任何j超出界限,因为向量中的所有字符串都被初始化为""空字符串.