二进制运算转换-G++不编译,但VS编译

Transform with Binary Operation - G++ does not compile but VS does

本文关键字:编译 VS 转换 -G++ 二进制运算      更新时间:2023-10-16

下面的代码是我做的一个简单测试,看看我是否可以编译transform。代码编译并在visualstudio:上正确输出此答案

firsta
secondb
thirdc

但是使用g++main.cpp-o main给了我这些错误:

main.cpp: In function 'int main()':
main.cpp:19:106: warning: lambda expressions only available with -std=c++0x or -std=gnu++0x [enabled by default]
main.cpp:19:107: error: no matching function for call to 'transform(std::vector<std::basic_string<char> >::iterator, std::vector<std::basic_string<char> >::iterator, std::vector<std::basic_string<char> >::iterator, std::vector<std::basic_string<char> >::iterator, main()::<lambda(const string&, const string&)>)'
main.cpp:19:107: note: candidates are:
/usr/include/c++/4.6/bits/stl_algo.h:4871:5: note: template<class _IIter, class _OIter, class _UnaryOperation> _OIter std::transform(_IIter, _IIter, _OIter, _UnaryOperation)
/usr/include/c++/4.6/bits/stl_algo.h:4907:5: note: template<class _IIter1, class _IIter2, class _OIter, class _BinaryOperation> _OIter std::transform(_IIter1, _IIter1, _IIter2, _OIter, _BinaryOperation)
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
#include <iterator>
#include <iostream>
using namespace std;
int main()
{
    vector<string> v, v2, v3;
    v.push_back("first"); v.push_back("second"); v.push_back("third");
    v2.push_back("a"); v2.push_back("b"); v2.push_back("c");
    v3.resize(3);

    transform(v.begin(), v.end(), v2.begin(), v3.begin(), [](const string &a, const string &b){return a + b;});
    copy(v3.begin(), v3.end(), ostream_iterator<string>(cout, "n"));
}

再次阅读此警告:

main.cpp:19:106: warning: lambda expressions only available with -std=c++0x or -std=gnu++0x [enabled by default]

要在GCC中使用C++11功能,如果使用GCC 4.6或更低版本,则需要使用选项-std=c++0x,在4.7或更高版本中则需要使用-std=c++11

编译器消息所说的内容(阅读):

警告:lambda表达式仅适用于-std=c++0x或-std=gnu++0x

添加-std=c++0x标志后,这对我来说编译得很好。