用c++编写代码,1.读取一个文件,每一行只有1个string类型数据;把这个数据存储在一个容器A中 ;2. 用最快的方式实现,查找一个string变量是否存在于容器A中;
时间: 2024-02-24 14:59:32 浏览: 77
好的,我来回答你的问题。
第一部分,读取文件并将数据存储在容器A中,可以使用以下代码实现:
```c++
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
int main() {
std::ifstream infile("data.txt");
std::vector<std::string> A;
std::string line;
while (std::getline(infile, line)) {
A.push_back(line);
}
infile.close();
return 0;
}
```
其中,`data.txt`是存储数据的文件名,`A`是存储数据的容器,`line`是每一行读入的数据。
第二部分,查找一个string变量是否存在于容器A中,可以使用`std::find`算法来实现,如下所示:
```c++
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
int main() {
std::ifstream infile("data.txt");
std::vector<std::string> A;
std::string line;
while (std::getline(infile, line)) {
A.push_back(line);
}
infile.close();
std::string target = "hello";
if (std::find(A.begin(), A.end(), target) != A.end()) {
std::cout << "Found!" << std::endl;
} else {
std::cout << "Not found!" << std::endl;
}
return 0;
}
```
其中,`target`是要查找的字符串变量,`std::find`算法会在容器`A`中查找`target`,如果找到了返回`target`所在的迭代器,否则返回`A.end()`。
阅读全文
相关推荐


















