谁能告诉我如何将迭代器增加2?
iter++可用 - 我必须这样做iter+2吗?我怎样才能做到这一点?
当你说:std :: advance的行为是什么时候:
std::vector<int> foo(10,10);
auto i = foo.begin();
std::advance(i, 20);
Run Code Online (Sandbox Code Playgroud)
什么是价值我?是foo.end()?
鉴于int foo[] = {0, 1, 2, 3};我想知道指向过去"一个过去"的迭代器是否无效.例如:auto bar = cend(foo) + 1;
有大量的抱怨和警告,这是Stack Overflow问题中的"未定义行为",如下所示:c ++当过去结束迭代器时,迭代器+整数的结果是什么?不幸的是,唯一的来源是挥手.
我购买它的麻烦越来越多,例如:
int* bar;
Run Code Online (Sandbox Code Playgroud)
是未初始化的,但肯定不会调用未定义的行为,并且给定了足够的尝试,我确信我可以找到一个实例,其中未初始化的值bar具有相同的值cend(foo) + 1.
这里最大的困惑之一是我不会要求解除引用cend(foo) + 1.我知道这将是未定义的行为,标准禁止它.但是这样的答案:https://stackoverflow.com/a/33675281/2642059只引用解除引用这样的迭代器是非法的,不回答这个问题.
我也知道C++只保证它cend(foo)是有效的,但它可能会numeric_limits<int*>::max()在这种情况下cend(foo) + 1溢出.我对这种情况不感兴趣,除非它在标准中被调出,因为我们不能让迭代器超过"一个接一个结束".我知道这int*只是一个整数值,因此会受到溢出的影响.
我想从一个可靠的来源引用一个引用,即将迭代器移到"一个接一个"的元素之外是未定义的行为.
对于关联容器,++运算符可以将迭代器发送到集合的末尾吗?
例:
map<UINT32, UINT32> new_map;
new_map[0] = 0;
new_map[1] = 1;
map<UINT32, UINT32> new_iter = new_map.begin();
++new_iter;
++new_iter;
++new_iter;
++new_iter;
++new_iter;
++new_iter;
++new_iter;
Run Code Online (Sandbox Code Playgroud)
在这结束时,new_iter == new_map.end(),或者它最终是在伟大的未知?
注意:我知道这搞砸了而不是做事的方式.我正在研究一些WTF公司代码.
假设我们有一个名为datasize 的数组5.如果我们将此数组作为参数传递给std::end函数
int *ptr = std::end(data);
Run Code Online (Sandbox Code Playgroud)
它将返回指向数组中最后一个元素的内存位置的指针.
题
指针指向一个超过数组中最后一个元素的内存位置有什么意义?为什么不指向数组中的最后一个元素?
是否允许增加it已经存在的迭代器变量end(),即auto it = v.end()?
vector?++it可能幂等如果it==v.end()?我问,因为我偶然发现了这样的代码:
std::vector<int> v{ 1, 2, 3, 4, 5, 6, 7 };
// delete every other element
for(auto it=v.begin(); it<v.end(); ++it) { // it<end ok? ++it ok on end?
it = v.erase(it);
}
Run Code Online (Sandbox Code Playgroud)
它适用于g ++ - 6,但这不是证据.
对于一个人it<v.end()可能只能使用vectors,我想它应该it!=v.end()一般阅读.但是在这个示例中,当它已经结束时,将无法识别vif ++it的结尾.
我已经阅读了C++列表迭代器的文档,但无法弄清楚一件事:C++迭代器是否"安全"?我的意思是,一旦它到达列表中的最后一个现有元素,它是否会停止递增?
[]的
我有一个小问题。我想利用字符串中的双字母大写。我设法编译了一个程序,但没有成功。
#include <iostream>
#include <cctype>
#include <string>
std::string::iterator function(
std::string::const_iterator a,
std::string::const_iterator b,
std::string::const_iterator e)
{
for (; a < b; a++)
{
if (*a == *(a + 1))
{
toupper(*a);
toupper(*(a + 1));
}
}
}
int main()
{
std::string in = "peppermint 1001 bubbles balloon gum", out(100, '*');
auto e = function(in.cbegin(), in.cend(), out.begin());
int n = e - out.begin();
std::string s = out.substr(0, n);
bool b = (s == "pePPermint 1001 buBBles baLLOOn gum");
std::cout << std::boolalpha …Run Code Online (Sandbox Code Playgroud)