微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c++ 为向量中的每个字符串检查它是否包含子字符串

如何解决c++ 为向量中的每个字符串检查它是否包含子字符串

我需要编写一个程序来给出大正整数的算术运算结果。有 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(),[](const string& str) { return str.find("-") != std::string::npos; }) != operacje.end())
        {
            cout << "-" << endl;
        }
        else if (find_if(operacje.begin(),[](const string& str) { return str.find("*") != std::string::npos; }) != operacje.end())
        {
            cout << "*" << endl;
        }
        else if (find_if(operacje.begin(),[](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

/
-
/

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

解决方法

这样做

#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。会做错事。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。