c++ - Vectors 上的数组下标运算符

标签 c++ vector

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

    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它使用 [ ] 运算符来访问 vector 的值

最佳答案

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 函数,我会猜测一个空字符串会导致一个空 vector ,这意味着当您打印 tokens[0] 时,该元素实际上并不存在。在调用 getline 之前,您需要确保输入缓冲区为空。例如,您可以在输入号码后立即调用 cin.ignore()

您也可以放弃 operator>>,而只使用 getline。然后使用您喜欢的方法将字符串转换为数字。

关于c++ - Vectors 上的数组下标运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8773131/

相关文章:

r - 如何在不重复的情况下将多个 data.frame 中的一组向量集成为一个?

c++ - STL列表、 vector 和集合的底层数据结构是什么?

c++ - boost 和图形化

c++ - 创建一个非预定义大小的数组?

c++ - 安全地停止线程

c# - 如何将一个 3D 点与另一个 3D 点的距离调整给定距离

c++ - 对象围绕世界轴 OpenGL 的旋转

c++调用类的构造函数

C++ 字段的复制省略

c++ - std::vector size()-1 是否总是给出最后一个元素的索引?