std :: vector operator []与at()访问

时间:2014-09-10 12:14:54

标签: c++ vector operator-keyword stdvector

<的std ::向量>运算符[]与at()

=========================================

我读过somewhere,只有索引访问运算符[]和()成员函数之间的区别在于()也检查索引是否有效。但是,从以下代码中扣除,似乎存在差异

std::vector<std::string>* namesList = readNamesFile("namesList.txt");
std::vector<Rabbit> rabbits;

const int numNAMES = namesList->size();

for (int i = 0; i < 5; i++)
{
    rnd = rand() % numNAMES;
    rabbits.push_back(Rabbit(namesList[i]));
}

上面的代码抛出

error C2440: '<function-style-cast>' : cannot convert from 'std::vector<std::string,std::allocator<_Ty>>' to 'Rabbit'
1>          with
1>          [
1>              _Ty=std::string
1>          ]
1>          No constructor could take the source type, or constructor overload resolution was ambiguous

另外,如果我将鼠标悬停在上面(见下文)

rabbits.push_back(Rabbit(namesList[i]));

^^^^^^^我读了intelliSense:

Error: no instance of constructor "Rabbit::Rabbit" matches the argument list
 argument types are:  (std::vector<std::string, std::allocator<std::string>>)

但是,如果我使用at()访问vector,就像这样:(并且只修改了这一行)

rabbits.push_back(Rabbit(namesList->at(i)))

代码无需编译和运行时错误。有人可以详细说明吗?

P.S:以防万一我为.h和.cpp提供代码:http://pastebin.com/9MgNRd7m

2 个答案:

答案 0 :(得分:7)

namesList是一个指针;所以namesList[i]将它视为指向矢量数组的指针,从该数组中提供一个矢量。幸运的是,由于类型不匹配,这会产生编译时错误,而不是来自越界数组访问的未定义的运行时行为。

要下标它指向的向量,您需要首先取消引用指针:

(*namesList)[i]

或者,等效但可能不太可读,

namesList->operator[](i)

你应该考虑为什么readNamesFile首先返回一个指针。按值返回向量会更有意义。

答案 1 :(得分:1)

请注意,namesList[i]不是namesList->operator[](i)

namesList[i]更像是*(namesList+i)

您必须取消引用指针才能直接使用该函数:

rabbits.push_back(Rabbit((*namesList)[i]));
相关问题