比较2个不同大小的c ++矢量

时间:2018-04-05 16:41:35

标签: c++ vector

基本上,我有一个字符向量和一个行向量,我想比较字符和字符串,如果向量中的每个字符都可以在行向量中找到匹配项。例如,它打印位置。如果行的向量是ABCDEF,HIJKL和chars的向量是C,E,F,C程序打印0,2 0,4 0,5 0,2

我自己尝试过这样做,但我遇到了两个问题,一个问题。字符向量按顺序打印,两个。如果字符向量中有一个元素出现两次,那么它只打印一次位置。

https://i.imgur.com/6Eu49IH.png

这是输出 消息文件是这是一个测试消息,这是一个放入char矢量的文件。

书籍文件是

ABCDE FG

HIJKLMNO

PQRSTUVWXYZ

并且每一行都被放入行的向量

int main(int argc, char *argv[])
    string str;
    vector <string> bookVector;
    vector <char> messageVector;
    char c;
    ifstream message(argv[2]);
    ifstream book(argv[1]);
    ofstream outputFile(argv[3], ios::in | ios::binary);

    while (getline(book, str))
    {
        bookVector.push_back(str);
    }

    while (message.get(c))
    {
        messageVector.push_back(c);
    }

    for (int i = 0; i < bookVector.size(); i++) 
        for (int x = 0; x < bookVector[i].size(); x++) 
            if (find(messageVector.begin(), messageVector.end(), 
                     bookVector[i][x]) != messageVector.end()) {
                cout << "found a match at " << bookVector[i][x] <<
                        " at positions "<<i<<","<<x<< endl;
            }
} 

1 个答案:

答案 0 :(得分:1)

你可以这样做:

#include<iostream>
#include<string>
#include <vector>

int main()
{
    std::vector<std::string> book = { {"ABC"},{"DEF"},{"GHI"}, {"BFG"}, {"HELLO"} };
    std::vector<char> chars = { 'B', 'G', 'H' };

    for (int j = 0; j < chars.size(); j++)
    {
        for (int i = 0; i < book.size(); i++)
        {
            size_t offset = 0;
            while ((offset = book[i].find(chars[j], offset)) != std::string::npos)
            {
                std::cout << "Found " << chars[j] << " at " << i << "," << offset << std::endl;
                ++offset;
            }
        }
    }
    std::cin.get();
    return 0;
}

以上示例生成的输出:

Found B at 0,1
Found B at 3,0
Found G at 2,0
Found G at 3,2
Found H at 2,1
Found H at 4,0