【问题标题】:c++: Accessing the Elements of a Map of Strings and Boost Circular Buffersc++:访问字符串映射的元素并提升循环缓冲区
【发布时间】:2011-04-23 17:25:48
【问题描述】:

我正在编写一个程序,它将城市名称的文本文件读入向量,然后使用 stl::map 将每个城市与提升循环缓冲区相关联。我还有一个温度数据向量,在将其作为字符串从另一个文本文件中读取后,我将其转换为双精度类型。我想知道如何将这些数据输入我选择的循环缓冲区。例如,温度数据来自波士顿,所以我想将其放入与波士顿相关的循环缓冲区中。如果有人能告诉我如何做到这一点,我将不胜感激!这是我的代码。与地图有关的代码在底部附近。

#include < map >
#include < algorithm >
#include < cstdlib >
#include < fstream >
#include < iostream >
#include < iterator >
#include < stdexcept >
#include < string >
#include < sstream >
#include < vector >
#include < utility >
#include < boost/circular_buffer.hpp >

double StrToDouble(std::string const& s) // a function to convert string vectors to double.
{
    std::istringstream iss(s);
    double value;

    if (!(iss >> value)) throw std::runtime_error("invalid double");

    return value;
}

using namespace std;

int main()
{

    std::fstream fileone("tempdata.txt"); // reading the temperature data into a vector.

    std::string x;

    vector<string> datastring (0);

    while (getline(fileone, x))
    {
        datastring.push_back(x);
    }

    vector<double>datadouble;

    std::transform(datastring.begin(), datastring.end(), std::back_inserter(datadouble), StrToDouble); // converting it to double using the function



    std::fstream filetwo("cities.txt"); // reading the cities into a vector.

    std::string y;

    vector<string> cities (0);

    while (getline(filetwo, y))
    {
        cities.push_back(y);
    }

    map<string,boost::circular_buffer<double>*> cities_and_temps; // creating a map to associate each city with a circular buffer.

    for (unsigned int i = 0; i < cities.size(); i++)
    {
        cities_and_temps.insert(make_pair(cities.at(i), new boost::circular_buffer<double>(32)));
    }

    return 0;
}

【问题讨论】:

  • 感谢本杰明修复格式!

标签: c++ boost stl circular-buffer


【解决方案1】:

您可以使用一对迭代器初始化一个 circular_buffer,如下所示:

std::vector<double> v;
...
... // Fill v with data
...

boost::circular_buffer<double> cb(v.begin(), v.end());

我不确定你想如何在你的具体情况下应用它。你只有一个双打向量,但我不知道有多少个城市。如果你想将整个数据插入到循环缓冲区中,按照你的方式,它会是这样的:

cities_and_temps.insert(make_pair(
    cities.at(i),
    new boost::circular_buffer<double>(datadouble.begin(), datadouble.end())));

【讨论】:

  • 谢谢本杰明。我想知道是否可以使用 push_back 将向量加载到任意缓冲区中,例如属于波士顿的缓冲区。我知道我不能说for(int i=0; i&lt;datadouble.size(); i++) { Boston.push_back(datadouble.at(i)); } 基本上我只是想知道如何引用特定的缓冲区。我可以说 city_and_temps.at(2).second.push_back(datadouble.at(i)) 用数据向量加载与第二个城市关联的缓冲区吗?
  • @siegel:这是你想要的吗? cities_and_temps["Boston"]-&gt;push_back(doubledata[i]);如果你想通过整数索引来引用数据,那么map不是你想要的数据结构。 map 的目的本质上是用一些其他任意对象的索引替换数组的正常整数索引,在你的例子中,一个字符串。
  • 非常感谢!我想这就是我要找的。这很有帮助。
猜你喜欢
  • 2017-10-13
  • 1970-01-01
  • 1970-01-01
  • 2015-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-15
相关资源
最近更新 更多