我已经告诉别人,编写using namespace std;代码是错误的,我应该用std::cout和std::cin直接代替.
为什么被using namespace std;认为是不好的做法?是低效还是冒着声明模糊变量(与名称std空间中的函数具有相同名称的变量)的风险?它会影响性能吗?
回答如何自我复制载体?让我对迭代器失效有点困惑.一些文献说"如果使用insert,push_back等,则认为所有迭代器都无效".多数民众赞成,它可能会导致向量增长,从而使迭代器无效.那个我知道会有足够空间的特殊情况怎么样?
第一次尝试:
myvec.reserve(myvec.size()*3); //does this protect me from iterator invalidation?
vector<string>::iterator it = myvec.end();
myvec.insert(myvec.end(), myvec.begin(), it);
myvec.insert(myvec.end(), myvec.begin(), it);
Run Code Online (Sandbox Code Playgroud)
经过一些优秀的答案第二次尝试
auto size = myvec.size();
myvec.reserve(size*3); //does this protect me from iterator invalidation?
myvec.insert(myvec.end(), myvec.begin(), myvec.begin()+size);
myvec.insert(myvec.end(), myvec.begin(), myvec.begin()+size);
Run Code Online (Sandbox Code Playgroud)
经过更优秀的答案第三次尝试:
auto size = myvec.size();
myvec.reserve(size*3); //does this protect me from iterator invalidation?
back_insert_iterator< vector<string> > back_it (myvec);
copy (myvec.begin(),myvec.begin()+size,back_it);
copy (myvec.begin(),myvec.begin()+size,back_it);
Run Code Online (Sandbox Code Playgroud)
Josuttis的"C++标准库参考"引用了这句话:
插入或删除元素会使引用,引用和迭代器无效,这些引用,引用和迭代器引用以下元素.如果插入导致重新分配,则会使所有引用,迭代器和指针无效.
表明我的代码是安全的和定义的行为.标准中是否有一个保证这一点的段落?