c++ - 对使用从 C++ 文件中读取的值有帮助吗?

标签 c++ arrays file vector coordinates

我尝试编写的程序遇到了一些问题,我希望有人可以就如何处理我面临的问题提供一些指导......

到目前为止,这是我的代码:

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

using namespace std;

struct City
{
string name;
int x;
int y;
};

int main()
{
vector<City>Coord;

City entries[10];

ifstream fin("Locations.txt");

int nb_entries;

string name;

int x, y;

for(nb_entries = 0; fin.good() && nb_entries < 10; nb_entries++)

{

    fin >> entries[nb_entries].name;

    fin >> entries[nb_entries].x;

    fin >> entries[nb_entries].y;

    cout << "City: " << entries[nb_entries].name << ", ";

    cout << "x: " << entries[nb_entries].x << ", ";

    cout << "y: " << entries[nb_entries].y << ", " << endl;

}   

system("pause");

return 0;

这会读取我存储在文本文件中的坐标并将它们输出到屏幕。文本文件的格式如下:

城市 1 x1 y1

城市2 x2 y2

...

城市10 x10 y10

这个阶段的输出让我可以看到我的代码是否正常工作。我现在需要做的是在获得用户选择城市的输入后使用这些坐标。我曾尝试将坐标读入一个数组和一个 vector ,但我正在努力寻找将它们存储为值并稍后在程序中调用它们的最佳方法。我对编程和 C++ 还是个新手,所以非常感谢任何帮助!

最佳答案

一种选择是使用从城市名称到坐标对的 map ,如下所示:

#include <unordered_map>

unordered_map<string, pair<int,int> >    myMap;

您可以像这样将数据放入myMap:

myMap[cityName] = make_pair(x,y);

并且可以像这样记忆它们:

x = myMap[cityName].first;
y = myMap[cityName].second;

关于c++ - 对使用从 C++ 文件中读取的值有帮助吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33883517/

相关文章:

连续空间中的复杂结构偏移

php - 无论如何要告诉 postgres 数组中的数据类型?

每次我尝试将文本放入日志文件时,Java Logger 都会覆盖

python - 读取大文本文件而不立即将其读入 RAM

c++ - 如何使用 fseek() 进入一行的开头

c - 如何在 C 中使用二维指针数组来存储字符串?

c++ - 字符串变量 : "No operator << matches these operands" 的问题

c# - 将算法应用于多个文件

c++ - 使用 OpenCV C++ 将多个图像叠加到相同大小的基本图像上

c++ - gcc 需要大量内存来编译堆栈上非常大的对象的 c++ 文件