连接带有时间戳的向量整数作为C ++中的字符串?

时间:2013-11-14 01:18:08

标签: c++ string boost vector

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

基本上,我需要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> >()â

2 个答案:

答案 0 :(得分:2)

您希望将uint32_t迭代器引用的it转换为字符串

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

你不能简单地在字符串中附加一个整数,因为编译器正确地告诉你没有operator+(std::string&, uint32_t)

答案 1 :(得分:1)

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

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

如果您真的想要掌握字符串,则需要先将*it转换为std::string,然后再将其与其他std::string连接。请注意,使用std::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);
   // ...
}