[英]comparing 2 vectors of different sizes c++
基本上,我有一個chars向量和一個lines向量,我想將chars與這些行進行比較,如果向量中的每個字符都可以在lines向量中找到一個匹配項。 例如,它打印位置。 如果行向量是ABCDEF,HIJKL且字符向量是C,E,F,C,則程序將輸出0,2 0,4 0,5 0,2
我已經嘗試過自己做,但是遇到了兩個問題,一個。 字符向量被無序打印,另外兩個。 如果chars向量中有一個元素出現兩次,那么它只會打印一次位置。
https://i.imgur.com/6Eu49IH.png
這就是消息文件是THIS IS TEST MESSAGE的輸出,這是放入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;
}
}
您可以執行以下操作:
#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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.