小编use*_*799的帖子

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

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

c++ vector stdvector operator-keyword

-3
推荐指数
1
解决办法
790
查看次数

标签 统计

c++ ×1

operator-keyword ×1

stdvector ×1

vector ×1