【问题标题】:c++ for every string in vector check if it contains a substringc ++为向量中的每个字符串检查它是否包含子字符串
【发布时间】:2021-01-05 01:13:04
【问题描述】:

我需要编写一个程序,给出大正整数的算术运算结果。有 4 种基本运算需要考虑:加法 (+)、减法 (-)、乘法 (*) 和整数除法 (/)。标准输入的第一行包含一个整数 Z,它确定在接下来的行中定义的测试数量。每个测试占用标准输入的一行并包含一个算术动作的记录,即由动作运算符分隔的两个数字字符串(没有额外的空格)。数字序列的长度不超过 256 个字符。这就是我写到这一刻的内容:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
    int Z;
    string operacja(256,'\0');
    cin >> Z;
    vector <string> operacje;
    for (int i = 0; i < Z; i++)
    {
            cin >> operacja;
            operacje.push_back(operacja);
    }
    cout << "" << endl;
    for(auto it = begin(operacje); it != end(operacje); ++it)
    {
        if (find_if(operacje.begin(), operacje.end(), [](const string& str) { return str.find("+") != std::string::npos; }) != operacje.end())
        {
            cout << "+" << endl;
        }
        else if (find_if(operacje.begin(), operacje.end(), [](const string& str) { return str.find("-") != std::string::npos; }) != operacje.end())
        {
            cout << "-" << endl;
        }
        else if (find_if(operacje.begin(), operacje.end(), [](const string& str) { return str.find("*") != std::string::npos; }) != operacje.end())
        {
            cout << "*" << endl;
        }
        else if (find_if(operacje.begin(), operacje.end(), [](const string& str) { return str.find("/") != std::string::npos; }) != operacje.end())
        {
            cout << "/" << endl;
        }
    }
    return 0;
    
}

当我运行代码时,我得到了这个:

3
124/5
678-7
8/454545

-
-
-

我应该得到这个:

3
124/5
678-7
8/454545

/
-
/

有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: c++ vector foreach substring


    【解决方案1】:

    这样做

    #include <iostream>
    #include <string>
    #include <vector>
    #include <algorithm>
    
    using namespace std;
    
    int main()
    {
        vector <string> operacje;
        operacje.push_back("124/5");
        operacje.push_back("678-7");
        operacje.push_back("8/454545");
    
        for (const string& str: operacje)
        {        
            if (str.find("+") != string::npos)
            {
                cout << "+" << endl;
            }
            else if (str.find("-") != string::npos)
            {
                cout << "-" << endl;
            }
            else if (str.find("*") != string::npos)
            {
                cout << "*" << endl;
            }
            else if (str.find("/") != string::npos)
            {
                cout << "/" << endl;
            }
        }
        return 0;
    }
    

    只需遍历向量中的字符串并检查需要的字符。 find_if 本身就像一个循环,您根本没有使用外部 for 循环。结果是每次操作都是一样的,因为每次都从向量的开头开始。

    请注意,这种方法确实有一个致命的缺陷,因为- 可以用来表示负数而不是减数。所以5 * -3。会做错事。

    【讨论】:

      猜你喜欢
      • 2021-12-20
      • 2011-11-09
      • 2013-05-18
      • 2011-01-21
      • 1970-01-01
      • 2014-12-10
      • 1970-01-01
      • 2014-11-22
      • 2013-02-05
      相关资源
      最近更新 更多