2

我有一个类,它的方法应该返回一个字符串向量。getCommVector 方法必须将字符串数组的元素 push_back 到一个字符串向量中,然后该方法可以返回该字符串向量。当尝试将字符串元素添加到字符串向量时,我得到:

libc++abi.dylib: terminate called throwing an exception
2Program ended with exit code: 0

我不明白为什么我不能 push_back 字符串到向量。有任何想法吗?提前致谢!

感兴趣的代码段(根据建议编辑):

class Command {
public:
    //Command (std::string, bool, bool);
    void setOperators(std::string,bool, bool);
    void analyseCommand();
    Command();
    std::vector<std::string> getCommVector ();
private:
    int numOperators; //number of total commands
    int opCount; //current command number
    std::string input_string;
    bool field_command, byte_command;
    std::string commVector[3];
    std::vector<std::string> finalCommVector;
    void byte_analysis();
    void field_analysis();
    void decode_command();
    void syntax_error();
    void decode_error();
};


Command::Command() : numOperators(0), opCount(0),  field_command(false),byte_command(false)
{

}
std::vector<std::string> Command::getCommVector ()
{
    std::string s ="test";
    finalCommVector.push_back("s");
    return finalCommVector;
}

添加 SSCE:

class Command {
    public:
        //Command (std::string, bool, bool);
        void setOperators(std::string,bool, bool);
        void analyseCommand();
        Command();
        std::vector<std::string> getCommVector ();
    private:
        int numOperators; //number of total commands
        int opCount; //current command number
        std::string input_string;
        bool field_command, byte_command;
        std::string commVector[3];
        std::vector<std::string> finalCommVector;
        void byte_analysis();
        void field_analysis();
        void decode_command();
        void syntax_error();
        void decode_error();

};


Command::Command() : numOperators(0), opCount(0), field_command(false),byte_command(false)
{

}

void Command::syntax_error()
{
    std::cout<<"Incorrect Syntax Error: Usage: linuxcut -b num -f num \n";
    exit(EXIT_FAILURE);
}

void Command::decode_error()
{
    std::cout<<"Decode Error: Usage: linuxcut -b num -f num \n";
    exit(EXIT_FAILURE);
}


void Command::analyseCommand()
{
    if (byte_command) {
        //start byte command analysys
        byte_analysis();
    }
    else if (field_command)
    {
        //start field command analysys
        field_analysis();
    }
}




void Command::setOperators(std::string input_argument, bool is_field, bool is_byte)
{
    input_string = input_argument;

    field_command = is_field;
    byte_command = is_byte;
}

std::vector<std::string> Command::getCommVector ()
{

    std::string s = "ssd";
    finalCommVector.push_back(s);
    /*
    for (int i = 0; i<sizeof(commVector); i++)
    {

        if (commVector[i] != "")
        {
            //debug

            std::cout<<"asdas";
        }


    }
     */
    return finalCommVector;
}


void Command::byte_analysis()
{
    int next_state = 0;
    int dashCount = 0;
    int commVectIndex = 0;




    //iterate through string and check if the argument is valid
    for (int i= 0; i<input_string.length(); i++) {



        switch (next_state) {
            case 0: //start
                //if character is a number:
                if (isdigit(input_string.at(i)))
                {
                    //first elemnt of command commVector is number
                    commVector[commVectIndex]+=input_string.at(i);

                    //DEBUG
                    std::cout<<commVector[commVectIndex];
                    next_state = 1;
                }
                //if character is a dash:
                else if (input_string[i] == '-')
                {
                    //increment dashCount
                    dashCount++;
                    //if next character in input_string is a number continue
                    if (isdigit(input_string[i+1])) {
                        commVector[commVectIndex]+=input_string.at(i);
                        commVectIndex++;
                        next_state = 1;
                    }
                    else //else error
                    {
                        syntax_error();
                    }
                }
                //if it's niether: error!
                else
                {

                    syntax_error();
                }
                break;

            case 1:
                //if next character is a number:
                if (isdigit(input_string[i]))
                {
                    commVector[commVectIndex]+=input_string.at(i);
                    next_state = 1;
                }
                //if next character is dash
                else if (input_string[i] == '-'&& dashCount <= 3)
                {
                    dashCount++;
                    //increment commandVectIndex
                    commVectIndex++;
                    next_state = 2;
                    commVector[commVectIndex]+=input_string.at(i);
                    //increment commandVectIndex to accomodate next operation
                    commVectIndex++;
                }

                //if it's niether: error!
                else
                {

                    syntax_error();
                }
                break;

            case 2://previous character was dash
                //if next character is number
                if (isdigit(input_string[i]))
                {
                    commVector[commVectIndex]+=input_string.at(i);
                    next_state = 1;
                }

                //if it's niether: error!
                else
                {

                    syntax_error();
                }
                break;

            default:
                syntax_error();
                break;
        }

    }

}



void Command::field_analysis()
{

}
/*****************FUNCTIONS DEFINITIONS***************/

void print_usage() {
    std::cout<<"Incorrect Syntax Error: Usage: linuxcut -b num -f num \n";
}



/*****************END OF FUNCTIONS DEFINITIONS***************/


/***************** MAIN ***************/

int main(int argc, char *argv[]) {
    int opt= 0;
    std::string byte = "-1-2,2",field = "";
    std::string sub_arg_delimiter = ","; //delimiter for comma serparated arguments
    static bool complement = false;
    int diffOpt = 0; //stores the difference between optind  and argc to read filenames in command
    std::string fileName;
    //Specifying the expected options
    //The two options l and b expect numbers as argument
    static struct option long_options[] = {
        {"byte",      required_argument,       0,  'b' },
        {"field", required_argument,       0,  'f' },
        {"complement",    no_argument, 0,  0 },
        {0,           0,                 0,  0   }
    };

    Command testCommand;
    testCommand.setOperators("-2-", false, true);

    std::vector<std::string> trial = testCommand.getCommVector();


    std::cout<<"filename:"<<fileName<<std::endl;
    std::cout<<"Selected flags:\n"<< "b: "<< byte<<"\nf: "<<field<<"\ncomplement: "<<complement<<std::endl;


    return 0;
}
4

3 回答 3

5

您正在迭代超出数组大小的方式。sizeof(commVector)返回数组的大小(以字节为单位)。

如果你有可用的 C++11,你可以这样做:

for (const auto &s : commVector) {
  if (s != "") {
    // as before
  }
}

或者至少是这个(如果你只有部分 C++11 支持):

for (auto it = std::begin(commVector); it != std::end(commVector); ++it) {
  std::string s = *it;
  // the rest as before
}

如果没有 C++11,你至少可以这样做:

for (int i = 0; i < sizeof(commVector) / sizeof(commVector[0]); ++i) {
  // the rest as before
}

或者提供您自己的函数来获取正确的数组大小:

template <class T, size_t N>
size_t arraySize(const T (&)[N]) { return N; }

// Use:

for (size_t i = 0; i < arraySize(commVector); ++i) {
  // the rest as before
}
于 2013-10-14T12:42:09.497 回答
2
i<sizeof(commVector);

应该

i<countof(commVector);

如果为您的编译器定义了 countof/_countof。如果没有,你可以自己做,它通常定义为:

#define countof(a) (sizeof(a)/sizeof(a[0]))

我不会讨论在 C++ 中使用宏 :)

当然,如果您的数组具有固定数量的元素,您也可以使用常量,但我想这只是一个示例。

sizeof返回对象(在本例中为字符串数组)本身的大小,而不是向量内元素的数量。

因此,它等于数组元素的数量乘以单个字符串实例的大小,因此您尝试使用operator[].

这也坏了:

finalCommVector.push_back("s"); 

可能你的意思是:

finalCommVector.push_back(s);
于 2013-10-14T12:43:37.480 回答
0

如果您只需要std::string commVectoras a的数组std::vector<String>,则可以使用std::vecor::assign
finalCommVector.assign(commVector, commVector+3)
'3' 是数组的长度。

于 2013-10-14T12:49:36.413 回答