0

我正在尝试使用以下代码将当前时间戳(以毫秒为单位)与我在向量中的整数连接起来-

基本上,我需要timestamp.integer作为字符串

struct timeval tp;
gettimeofday(&tp, NULL);
uint64_t ms = tp.tv_sec * 1000 + tp.tv_usec / 1000;


struct timeval tp;
gettimeofday(&tp, NULL);
uint64_t ms = tp.tv_sec * 1000 + tp.tv_usec / 1000;

std::vector<uint32_t> myvector;
for (uint32_t i=1; i<=5; i++) myvector.push_back(i);

std::cout << "myvector contains:";

for (std::vector<uint32_t>::iterator it = myvector.begin() ; it != myvector.end(); ++it) {
       string id = boost::lexical_cast<std::string>(ms)+"."+*it; // this line gives me exception?
       std::cout << ' ' << id;
       std::cout << '\n';
}

我希望打印出来的结果是这样的字符串-

1384391287812.1
1384391287812.2
1384391287812.3
1384391287812.4
1384391287812.5

我得到的例外是 -

error: no match for âoperator+â in âstd::operator+(const std::basic_string<_CharT, _Traits, _Alloc>&, const _CharT*) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>](((const char*)".")) + it.__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator*<int*, std::vector<int> >()â
4

2 回答 2

2

您想将迭代器uint32_t引用的it内容转换为字符串

   string id = boost::lexical_cast<std::string>(ms)+"."+ boost::lexical_cast<std::string>(*it); 

您不能简单地将整数附加到字符串,因为operator+(std::string&, uint32_t)编译器正确地告诉您没有。

于 2013-11-14T01:24:29.630 回答
1

鉴于您打印了这些值,我不会费心将它们连接成std::string: 那只是浪费 CPU 周期和相当多的周期!相反,我只是将数据转储到输出中:

for (std::vector<uint32_t>::iterator it = myvector.begin() ; it != myvector.end(); ++it) {
   std::cout << ms << '.' << *it << '\n';
}

如果您真的想获取字符串,则需要先转换*it为 a std::string,然后再将其与 other 连接起来std::string。请注意, usingstd::lexical_cast<std::string>(x)可能不会太昂贵,但您仍应尽量减少其使用(尤其是当您尝试格式化它未专门针对的更有趣的类型时):

std::string base(boost::lexical_cast<std::string>(ms) + ".");
for (std::vector<uint32_t>::iterator it = myvector.begin() ; it != myvector.end(); ++it) {
   string id = base + boost::lexical_cast<std::string>(*it);
   // ...
}
于 2013-11-14T01:29:45.977 回答