【问题标题】:Access elements of boost tokenizerboost tokenizer 的访问元素
【发布时间】:2013-10-22 18:05:29
【问题描述】:

我正在尝试使用 boost 将文件的列分配给 std::map。我想将每行中的元素 0 分配给索引,将元素 2 分配给值。没有迭代器有没有办法做到这一点? addr_lookup 行不起作用。

#include <iostream>
#include <fstream> 
#include <string>
#include <map>
#include <boost/tokenizer.hpp>
#include <boost/lexical_cast.hpp>

int main()
{
  std::ifstream myfile("core_info_lowbits.tab", std::ios_base::in);
  std::string line;
  typedef boost::tokenizer<boost::char_separator<char> >  tokenizer;
  boost::char_separator<char> sep(" ");
  std::map<std::string, unsigned int> addr_lookup;

  while ( std::getline (myfile,line) )
  {
    tokenizer tokens(line, sep);
    //Line below does not work
    addr_lookup[*tokens.begin()] = boost::lexical_cast<unsigned int> (*(tokens.begin()+2));
    for (tokenizer::iterator tok_iter=tokens.begin();
         tok_iter != tokens.end(); ++tok_iter)
          std::cout << *tok_iter << std::endl;
  }
}

【问题讨论】:

  • 所以我将它转换为 std::vector 可以工作但不确定它是否是好的编程风格:std::vector<:string> s_tmp(tokens.begin(), tokens。结束());
  • 因为您可以增加 std::vector 的迭代器

标签: c++ boost tokenize


【解决方案1】:

您正在尝试使用+ 推进迭代器,这是不可能的

用途:

tokenizer::iterator it1,it2= tokens.begin();
it1=it2;
++it2; ++it2;

addr_lookup[*it1] = boost::lexical_cast<unsigned int> (*it2);

或者简单地说,

tokenizer::iterator it1,it2= tokens.begin();
it1=it2;
std::advance(it2,2);
addr_lookup[*it1] = boost::lexical_cast<unsigned int> (*it2);

【讨论】:

  • 需要递增两次(OP 表示索引 2 处的元素)。
  • std::advance 怎么样? :)
猜你喜欢
  • 2011-12-17
  • 1970-01-01
  • 2012-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-21
相关资源
最近更新 更多