vector的out_of_range exception

今天碰到一个复位问题,log中的信息是:

terminate called after throwing an instance of 'std::out_of_range'

  what():  vector::_M_range_check

从网上找到对应的错误,应该是vector随机索引时越界导致的异常。

(http://my.oschina.net/xinxingegeya/blog/228316

    //下标操作和安全的随机访问

    //提供快速随机访问的容器(string,vector,deque和array)也都提供下标运算符
    vector<int> ivec = {1,2,45,13};
    cout<<ivec.at(4)<<endl; //抛出异常,下标越界
    //terminate called after throwing an instance of 'std::out_of_range'
    //what():  vector::_M_range_check

发生错误的原因是收到一条消息中有IP地址:<ipAddress>192.168.255.129</ipAddress>

而在处理函数中,实际希望其中带Port,代码也是按携带Port处理的:

std::vector<std::string> hostPortStrings;
boost::algorithm::split(hostPortStrings, authority, boost::is_any_of(":"),
boost::algorithm::token_compress_on);
int port;
std::stringstream ss;
ss << hostPortStrings.at(1);  //--这里会越界
ss >> port;
return HostAndPort(hostPortStrings.at(0), port);

这里还涉及到boost的split的功能

http://www.boost.org/doc/libs/1_55_0/doc/html/string_algo/usage.html#idp206847064

    string str1("hello abc-*-ABC-*-aBc goodbye");

    typedef vector< iterator_range<string::iterator> > find_vector_type;
    
    find_vector_type FindVec; // #1: Search for separators
    ifind_all( FindVec, str1, "abc" ); // FindVec == { [abc],[ABC],[aBc] }

    typedef vector< string > split_vector_type;
    
    split_vector_type SplitVec; // #2: Search for tokens
    split( SplitVec, str1, is_any_of("-*"), token_compress_on ); // SplitVec == { "hello abc","ABC","aBc goodbye" }

token_compress_on:

http://www.cnblogs.com/nzbbody/p/3410264.html

对于场景:string s = "123456",用"3","4"切分,默认情况下(boost::token_compress_off),切分结果为12,空,56,注意,这里的空不是空格。而是"3","4"之间的空。如果不想要这个空,指定boost::token_compress_on就行了。

boost::token_compress_on的意思就是说,以"3","4",切分,当出现34的时候,就把34压缩成整体,用"34"切分。

posted @ 2014-10-14 13:52  codel_1220  阅读(975)  评论(0编辑  收藏  举报