将数据加载到结构的向量中

时间:2011-05-03 00:47:55

标签: c++ vector struct

我正在尝试制作一个基本的文本编辑器,但我在使用push_back加载结构中的数据时遇到了问题。

这是结构

struct LineInfo
{       
    int lineNumber;         
    string text;            
};

这是主程序

vector<LineInfo> globalDocument;

int main()
{
    cout << "COSC 120 line editing system now running." << endl << endl;
    bool done = false;
    while ( !done )
    {
        cout << "> ";
        string inputBuffer;
        getline( cin, inputBuffer );
        int lineNumber;
        splitLineNumberAndText( inputBuffer, lineNumber );
        ptr.push_back( &lineNumber );
        if ( lineNumber > 0 )
            handleTextLine( inputBuffer, lineNumber );
        else
            done = handleSystemCommand( inputBuffer );
    }

    cout << endl << "COSC 120 line editing system has shut down. Bye." << endl;
    return 0;
}

这会从输入中接收行号和文本,然后将其拆分为int和string并将其发送到handleTextLine

这是函数

void handleTextLine( const string& s, int lineNumber2 )
{
    globalDocument.lineNumber.push_back(lineNumber2);
    globalDocument.text.push_back(s);
}

1 个答案:

答案 0 :(得分:2)

vector<LineInfo> globalDocumentLineInfo结构的向量,因此您必须将LineInfo个对象推入其中:

void handleTextLine( const string& s, int lineNumber2) {
    LineInfo li;
    li.lineNumber = lineNumber2;
    li.text = s;
    globalDocument.push_back(li);
}

或者,使用struct初始化语法:

void handleTextLine( const string& s, int lineNumber2) {
    LineInfo li = {lineNumber2, s};
    globalDocument.push_back(li);
}

如果为LineInfo声明构造函数,则可以获得更紧凑的插入代码:

struct LineInfo {

    // Default constructor
    LineInfo() : lineNumber(0) {}

    // Constructor taking 2 arguments
    LineInfo(int n, string s) : lineNumber(n), text(s) {}

    int lineNumber;
    string text;
};

void handleTextLine( const string& s, int lineNumber2) {
    globalDocument.push_back(LineInfo(lineNumber2, s));
}