std::vector运算符[]与at()访问
std::vector operator [] vs. at() access
<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]));
相关文章:
- 通过方法访问结构
- 使用不带参数的函数访问结构元素
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- 用于访问容器<T>数据成员的正确 API
- 访问者访问变体并返回不同类型时出错
- 尝试通过多个向量访问变量时,向量下标超出范围
- 无法访问嵌套类.类的使用无效
- 当键值是 std 向量时,为什么使用 at in C++ 访问映射值如此缓慢?
- 使用 at() 访问 std::map 元素是否比运算符 [] 慢?
- OpenCV 像素访问点与 at() - 不同的值
- 通过操作员[]和.at()访问向量的负索引
- 访问图像像素;MatIterator_<> 和 Mat::at 运算符的比较
- c at()函数class string访问紫色的函数
- 如何从OpenCV Mat访问浮点值(.at和.ptr除外)
- std::vector运算符[]与at()访问
- 测试容器是否实现.at()成员访问/ std::sort兼容的正确方法
- 是c++ 11中map标准的at() const访问器
- 使用std::vector::at或std::vector::operator[]访问vector:中存储的对象
- C++OpenCV mat.at在使用数据时产生访问冲突
- 我应该使用括号 [] 还是 .at() 进行数组访问