繁体   English   中英

向量上的数组下标运算符

[英]Array subscript operator on Vectors

我正在编写一个代码来标记字符串wrt deimeters“,”。

    void Tokenize(const string& str, vector<string>& tokens, const string& delimeters)
    {
      // Skip delimiters at beginning.
      string::size_type lastPos = str.find_first_not_of(delimiters, 0);
      // Find first "non-delimiter".
      string::size_type pos     = str.find_first_of(delimiters, lastPos);

      while (string::npos != pos || string::npos != lastPos)
      {
         // Found a token, add it to the vector.
         tokens.push_back(str.substr(lastPos, pos - lastPos));
         // Skip delimiters.  Note the "not_of"
         lastPos = str.find_first_not_of(delimiters, pos);
         // Find next "non-delimiter"
        pos = str.find_first_of(delimiters, lastPos);
      }
    }

    int main()
    {
       string str;
       int test_case;
       cin>>test_case;
       while(test_case--)
       {
           vector<string> tokens;
           getline(cin, str);
           Tokenize(str, tokens, ",");
           // Parsing the input string 
           cout<<tokens[0]<<endl;
       }
       return 0;
    }

它给出了运行时的分段错误。 当我调试它的线

    cout<<tokens[0]<<endl 

是问题的原因。我无法理解为什么因为在cplusplus.com它使用[]操作符来访问向量的值

使用std::getline()的读取是否可能不成功? 在这种情况下,字符串将为空,使用下标运算符将崩溃。 尝试阅读后,您应该始终测试阅读是否成功,例如:

if (std::getline(std::cin, str)) {
    // process the read string
}
cin>>test_case; // this leaves a newline in the input buffer
while(test_case--)
{
    vector<string> tokens;
    getline(cin, str); // already found newline
    Tokenize(str, tokens, ",");  // passing empty string

在不查看Tokenize函数的情况下,我猜测空字符串会导致空向量,这意味着当您打印tokens[0] ,该元素实际上不存在。 在调用getline之前,您需要确保输入缓冲区为空。 例如,您可以在输入数字后cin.ignore()拨打cin.ignore()

你也可以放弃operator>> ,只使用getline。 然后使用您喜欢的方法对字符串进行数字转换。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM