这是我的代码,它试图在 vector 的最后四个元素中搜索字符字符串“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 array\n";
}
}
最佳答案
只要您的 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 array\n";
}
如@DavidHammen 所述,sizeof(tofind2)
仅在 sizeof(tofind2[0]) == 1
时有效.有一些比较好写template
s 找到数组的大小并且没有那个弱点,例如:
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&
)
关于c++ - 是否可以引用从 end() 中减去的 std::vector 的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17326479/