C++ Code Possible Issues -



C++ Code Possible Issues -

are there errors in code below?

#include <vector> #include <iostream> #include <string> #include <algorithm> #include <functional> int main() { std::vector<std::string> myvector; myvector.push_back("one"); myvector.push_back("two"); myvector.push_back("three"); myvector.push_back("four"); myvector.push_back("five"); std::sort(myvector.begin(),myvector.end(),std::less_equal<std::string>()); std::string& str = myvector.back(); std::cout << str << std::endl; std::vector<std::string>::const_iterator = myvector.begin(); myvector.push_back("six"); myvector.push_back("seven"); std::cout << *it << std::endl; homecoming 0; }

i see assigning address of lastly element of vector str means if remove element str empty, , can cause united nations expected behaviour , run time issues.

yes there, problem line:

std::cout << *it << std::endl;

that comes after several push_backs. since vector resizeable, possible between saving off iterator , adding more elements, container had allocate more memory. if did have to, iterator pointing element no longer part of vector. may not it, have [potentially] dangling pointer.

also, same with:

std::string& str = myvector.back();

that reference become invalidated after push_backs.

c++

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -