簡體   English   中英

c++ 為向量中的每個字符串檢查它是否包含 substring

[英]c++ for every string in vector check if it contains a substring

我需要編寫一個程序,給出大正整數的算術運算結果。 有 4 種基本運算需要考慮:加法 (+)、減法 (-)、乘法 (*) 和整數除法 (/)。 標准輸入的第一行包含一個 integer 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

/
-
/

有人可以幫我解決這個問題嗎?

像這樣做

#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 會做錯事。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM