std::vector运算符[]与at()访问

std::vector operator [] vs. at() access

本文关键字:at 访问 vector 运算符 std      更新时间:2023-10-16

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

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

我在某个地方读到,的索引访问运算符[]和成员函数at()之间的唯一区别是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]));
}

上面的代码抛出

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]));

 nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp ^^^^^^ nbsp nbsp;我读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

namesList是一个指针;因此namesList[i]将其视为指向向量数组的指针,给出该数组中的向量。幸运的是,这会由于类型不匹配而导致编译时错误,而不是由于越界数组访问而导致未定义的运行时行为。

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

(*namesList)[i]

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

namesList->operator[](i)

您应该首先考虑readNamesFile返回指针的原因。按值返回向量更有意义。

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

CCD_ 6更像CCD_。

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

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