微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – 将int的向量转换为str的向量

我正在尝试转换一个向量< int>到矢量< string>.使用std :: transform我使用std :: to_string将int转换为字符串,但我不断收到错误.这是我的代码
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>

int main(){
    std::vector<int> v_int;
    std::vector<std::string> v_str;

    for(int i = 0;i<5;++i)
        v_int.push_back(i);

    v_str.resize(v_int.size());
    std::transform(v_int.begin(),v_int.end(),v_str.begin(),std::to_string);
}

但我收到这个错误

no matching function for call to 'transform'
        std::transform(v_int.begin(),std::to_string);
        ^~~~~~~~~~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/algorithm:1951:1: note: 
      candidate template ignored: Couldn't infer template argument
      '_UnaryOperation'
transform(_InputIterator __first,_InputIterator __last,_OutputIterato...
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/algorithm:1961:1: note: 
      candidate function template not viable: requires 5 arguments,but 4 were
      provided
transform(_InputIterator1 __first1,_InputIterator1 __last1,_InputItera...

解决方法

std::to_string一个超载的功能,所以你需要提供一个演员来消除歧义
std::transform(v_int.begin(),static_cast<std::string(*)(int)>(std::to_string));

或使用lambda

std::transform(v_int.begin(),[](int i){ return std::to_string(i); });

原文地址:https://www.jb51.cc/c/115377.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐