为什么这个向量不能给我与数组相同的输出?

sri*_*714 1 c++ vector

如果一个向量只是一个功能更强大的数组,那么就像一个数组一样,它会将基本元素的地址存储在它的名字中吗?为什么我没有得到存储在指定索引位置的元素的值,而是将完整的字符串作为输出?这是我的代码!

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<string> v(20,"hello");
     char a[]={"hello"};

    cout<<v[1]<<"\n"; //this gives hello as the output

    cout<<a[1];       //this gives e


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

Jer*_*fin 6

你在这里定义完全不同的类型.

vector<string> v(20,"hello");
Run Code Online (Sandbox Code Playgroud)

这将创建一个包含20个字符串的向量,每个字符串初始化为包含"hello".向量的每个元素都是一个完整的字符串.

char a[]={"hello"};
Run Code Online (Sandbox Code Playgroud)

这将创建一个包含"hello"的(C风格)字符串.数组的每个元素都是单个字符.

当然,当您要求打印出一个字符串时,整个字符串都会打印出来.同样,当您要求打印单个字符时,会打印出一个字符.