【问题标题】:C++ string _Xout_of_range("invalid string position");C++ string _Xout_of_range("无效的字符串位置");
【发布时间】:2020-01-21 13:58:53
【问题描述】:

我是 C++ 新手。我有一个任务要求我根据输入执行一系列操作。代码似乎可以工作,但当我的字符串大小达到 16 时停止。尝试了 2 个测试用例。

输入是一个整数,后跟换行符,后跟字母数字+空格+'['或']'或'

1
my ]]name]] is]] joha<n]<n doe]]]]]

代码:

int main() {
    int TC; cin >> TC; cin.get(); //absorb newline
    while (TC--) {
        string s1;
        string::iterator itr = s1.begin(); //move using iterators
        while (1) {
            char c;
            cin.get(c);
            if (c == '[') { //move to first element
                itr = s1.begin();
            }
            else if (c == ']') { // move to last element
                itr = s1.end();
            }
            else if (c == '<') {
                if (s1.length() > 0) {
                    itr--;
                    s1.erase(itr); //erase current position
                }
            }
            else if (c == '\n') { //cout at newline char
                cout << s1 << endl;
                break;
            }
            else {  //add to string
                s1.insert(itr, c);
                itr++;
            }
            cout << s1 << ' ' << s1.size() << endl; //checking
        }
    }
    return 0;
}

【问题讨论】:

  • 调用erase或insert后迭代器失效。
  • 作业到底是什么?不管是什么,我敢打赌你做错了,有更容易/更好/更不容易出错的方法来完成你想要完成的任何事情。
  • 另外,也许您应该根据说明从旧字符串构建 new 字符串,而不是尝试操纵原始字符串。如您所见,更改现有字符串很容易出错(正如我在第一条评论中所建议的那样)。
  • @Hao Long 您需要使用迭代器还是可以使用索引?

标签: c++ string iterator char inputstream


【解决方案1】:

使用诸如插入或擦除迭代器之类的操作后可能会失效。

您需要使用从这些成员函数返回的迭代器。

这是一个演示程序。

#include <iostream>
#include <string>
#include <limits>
#include <sstream>

int main() 
{
    std::string input( "1\nmy ]]name]] is]] joha<n]<n doe]]]]]\n" );

    std::istringstream iss( input );

    size_t n;

    iss >> n;
    iss.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );

    while ( n-- )
    {
        std::string s;
        char c;

        auto it = s.end();
        while ( iss.get( c ) && c != '\n' )
        {
            switch ( c )
            {
            case ']':
                it = s.end();
                break;

            case '[':
                it = s.begin();
                break;

            case '<':
                if ( it != s.begin() )
                {
                    it = s.erase( --it );
                }                   
                break;

            default:
                it = s.insert( it, c );
                ++it;
                break;
            }
        }

        std::cout << s << '\n';
    }

    return 0;
}

它的输出是

my name is john doe

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-04
    • 2018-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多