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

use*_*799 -3 c++ vector stdvector operator-keyword

<std :: Vector> Operator [] vs. at()

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

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

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]));
}
Run Code Online (Sandbox Code Playgroud)

上面的代码抛出

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
Run Code Online (Sandbox Code Playgroud)

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

rabbits.push_back(Rabbit(namesList[i]));
Run Code Online (Sandbox Code Playgroud)

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

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

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

rabbits.push_back(Rabbit(namesList->at(i)))
Run Code Online (Sandbox Code Playgroud)

代码工作没有编译和运行时错误.有人可以详细说明吗?

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

Mik*_*our 7

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

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

(*namesList)[i]
Run Code Online (Sandbox Code Playgroud)

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

namesList->operator[](i)
Run Code Online (Sandbox Code Playgroud)

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