引用从end()中减去的std::向量的一部分可以吗
Is it ok to reference a part of a std::vector subtracted from end()
这是我的代码,它试图在向量的最后四个元素中搜索一个字符串"gold"。它确实成功地找到了字符串,但这样做安全吗?它适用于MS VS2008。
#include <vector>
#include <iostream>
int main() {
char random[] = {'a','b','c','d','e','f','g'};
char tofind2[] = {'g','o','l','d'};
std::vector<char> buf;
buf.insert(buf.end(), random, random+sizeof(random));
buf.insert(buf.end(), tofind2, tofind2+sizeof(tofind2));
if(buf.size() >= sizeof(tofind2) && std::equal(buf.end()-sizeof(tofind2), buf.end(), tofind2)) {
std::cout << "found value in last " << sizeof(tofind2) << " elements of arrayn";
}
}
只要vector
中至少有4个元素,这是安全的:迭代器通常可以通过其范围的边界移动,随机访问迭代器可以通过整数类型的加法/减法移动。std::vector
的迭代器是随机访问迭代器。
如果它的元素少于4个,这是不安全的,并导致未定义的行为(甚至在您取消引用迭代器之前!)
如果你想小心的话,你应该检查一下那个箱子。
template<typename Container>
auto nth_last_iterator( Container&& c, int n )
-> declval( std::begin(c) )
{
if (n > std::end(c) - std::begin(c))
n = std::end(c) - std::begin(c);
return std::end(c)-n;
}
它是C++11并且在任何随机访问容器上工作。然后你得到:
if(std::equal(nth_last_iterator(buf,sizeof(tofind2)), buf.end(), tofind2)) {
std::cout << "found value in last " << sizeof(tofind2) << " elements of arrayn";
}
正如@DavidHammen所指出的,sizeof(tofind2)
仅在sizeof(tofind2[0]) == 1
的情况下有效。有一些相对容易编写的template
可以找到阵列的大小,并且没有这种弱点,例如:
template<typename T, std::size_t N>
std::size_t lengthof( T(&)[N] ) {
return N;
}
它是有效的C++03,在C++11中可以使它成为constexpr
。(您也可以将其扩展到std::array< T, N > const&
)
这是正确的,因为允许迭代器算术,所以可以安全地这样做(http://www.cplusplus.com/reference/iterator/RandomAccessIterator/)。
相关文章:
- std::向量与传递值的动态数组
- 如何在旧c++中初始化const-std向量
- 如何检查两个 std::向量在小于 O(n) 的时间复杂度内是否相等
- 当键值是 std 向量时,为什么使用 at in C++ 访问映射值如此缓慢?
- 如何初始化 std::向量的映射?
- 迭代时将指向differents类型的指针保存在std::向量中
- std::向量迭代器和调整大小/保留的奇怪/有趣行为
- yaml-cpp到std::向量迭代的怪异行为
- 故意泄漏std::向量的内存
- 调整STD ::向量的大小是否可以降低其能力
- std ::向量距离函数如何给出比.size()更高的值
- C++ std::向量插入两个元素替代算法失败
- 错误:数字常数之前的预期无限制ID:std :: array和std ::向量大小分配
- 在我提供的此示例中,如何将2维std ::向量的逻辑更改为具有向量[row] [col] [col] [col] [co
- GUI滑块的动态数量,该数量更新具有回调中值的std ::向量
- 是一个std ::向量线程,我的目的是安全的
- 将具有std ::向量的C 函数称为Julia的输入和输出参数
- 将std ::向量作为指针参考
- STD ::向量如何调整其内部缓冲区大小
- 在C 中,是否有可能在不兼容类型的std ::向量对象之间传输不同类型的缓冲区