【发布时间】:2016-04-01 16:53:48
【问题描述】:
如果向量只是一个功能更强大的数组,那么就像数组一样,它是否将基元素的地址存储在其名称中?为什么我没有得到存储在指定索引位置的元素的值,而是得到了完整的字符串作为输出? 这是我的代码!
#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;
}
【问题讨论】:
-
A
std::vector<std::string>甚至与char []不同,因为它是字符串的集合而不是单个字符串(v的每个元素都是std::stringa的每个元素都是char)。 -
vector<string> v(20,"hello");您正在创建 20 个 std::strings 并打印第二个。char a[]={"hello"};您正在创建一个字符数组并打印第二个字符。