【问题标题】:iterating vector of strings C++字符串 C++ 的迭代向量
【发布时间】:2015-09-26 07:27:27
【问题描述】:

代码是从文本文件中读取指令并打印出图形模式。一是我的功能无法正常工作。该功能是将我从文件中获得的字符串向量读取到结构中。

以下是我的输出,我的第二、第三和第六个图是错误的。似乎第二个和第三个向量没有放置正确的行号和列号;最后一个按字母顺序跳过了“e”。 试了很多次,还是找不到问题。

  typedef struct Pattern{
    int rowNum;
    int colNum;
    char token;
    bool isTriangular;
    bool isOuter;
}Pattern;
void CommandProcessing(vector<string>& , Pattern& );
int main()
{
 for (int i = 0; i < command.size(); i++)
    {
        Pattern characters;
        CommandProcessing(command[i], characters);

    }

    system("pause");
    return 0;
}

 void CommandProcessing(vector<string>& c1, Pattern& a1)
    {
        reverse(c1.begin(), c1.end());
        string str=" ";


        for (int j = 0; j < c1.size(); j++)
        {

            bool foundAlpha = find(c1.begin(), c1.end(), "alphabetical") != c1.end();
            bool foundAll = find(c1.begin(), c1.end(), "all") != c1.end();
            a1.isTriangular = find(c1.begin(), c1.end(), "triangular") != c1.end() ? true : false;
            a1.isOuter = find(c1.begin(), c1.end(), "outer") != c1.end() ? true : false;

            if (foundAlpha ==false && foundAll == false){
                a1.token = '*';
            }
            //if (c1[0] == "go"){
            else if (c1[j] == "rows"){
                str = c1[++j];
                a1.rowNum = atoi(str.c_str());
                j--;
            }
            else if (c1[j] == "columns"){
                str = c1[++j];
                a1.colNum = atoi(str.c_str());
                j--;
            }
            else if (c1[j] == "alphabetical")
                a1.token = 0;

            else if (c1[j] == "all"){
                str = c1[--j];
                a1.token = *str.c_str();
                j++;
            }

        }

    }

【问题讨论】:

    标签: c++ vector


    【解决方案1】:

    在调试(或发布)您的代码之前,您应该尝试使其更简洁。它包含许多奇怪/不必要的部分,使您的代码更难理解(并导致您刚才描述的错误行为)。

    例如,你有一个 if 开头:

    if (foundAlpha ==false &amp;&amp; foundAll == false){

    如果没有 alpha 和 all 命令,则在整个循环长度内始终为 true,并且其他命令都放在 else if 语句中。 他们不会被处决。

    因此,在您的第二个和第三个示例中,除了isTriangularisOuter 标志之外,不会读取任何命令。

    考虑以下更改,而不是像这样的混合结构:

    • 为您的 Pattern 结构添加一个默认构造函数,初始化其成员。例如,如果将 token 初始化为 *,则可以删除它,甚至删除它所需的两个 bool 变量。
    • 始终以一种方式进行解析 - 最简单的方法是将三角形和外部 bool 移动到与其他结构相同的 if 结构。 (或者如果您真的想保留这个 find 查找,请将它们移到 for 循环之前 - 您只需设置一次!)
    • 永远不要不要修改你的循环变量,这是一个错误磁铁!好的,这条规则有一些罕见的例外,但这不是其中之一。

      你可以写str = c1[j+1],而不是str = c1[++j];,然后递减。

    • 另外,您确定需要那个reverse 吗?这使您的相对 +/-1 索引不清楚。例如,c1[j+1 在原始命令字符串中为 j-1

    关于最后一个:这可能是您的outer 打印代码中的一个错误,您没有发布。

    【讨论】:

    • 谢谢!我使用您的建议修复了我的代码并且它有效
    猜你喜欢
    • 2017-07-25
    • 2021-04-01
    • 1970-01-01
    • 2016-08-08
    • 1970-01-01
    • 1970-01-01
    • 2011-07-22
    • 2023-04-10
    • 2015-01-13
    相关资源
    最近更新 更多