2014-10-31 31 views
2

下面的代碼中是否有任何錯誤?C++代碼可能的問題

#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 it = myVector.begin(); 

    myVector.push_back("six"); 
    myVector.push_back("seven"); 

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

    return 0; 
} 

我只能看到通過指定向量的最後一個元素的地址爲str這意味着,如果刪除該元素則str是空的,而這可能會導致未預期的行爲,甚至是運行時間的問題。

+2

在'push_back'之後調用迭代器和內部引用到'std :: vector'中。 – sjdowling 2014-10-31 11:49:52

+0

'std :: less_equal'不提供必要的嚴格弱排序。它不是自反的(x≤x不是假的)。 – chris 2014-10-31 11:50:22

+0

這絕對是反身性的。這是問題。 – Barry 2014-10-31 11:52:47

回答

2

是有的,問題是這一行:

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

那幾經push_back s下次上。由於vector是可調整大小的,所以在保存迭代器和添加更多元素之間,容器必須分配更多內存是可能的。如果確實需要,那麼你的迭代器會指向一個不再是vector的一部分的元素。它看起來可能不是很清楚,但是你可能有一個懸掛的指針。

此外,與相同:

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

該引用可以在push_back年代後變得無效。