引用从end()中减去的std::向量的一部分可以吗

Is it ok to reference a part of a std::vector subtracted from end()

本文关键字:std 向量 一部分 end 引用      更新时间:2023-10-16

这是我的代码,它试图在向量的最后四个元素中搜索一个字符串"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/)。