C ++ std :: transform of pairs-> first to new vector

时间:2012-02-01 10:18:26

标签: c++ vector transform functor std-pair

抱歉有点初学者问题。有对的矢量和矢量

typedef std::vector <int> TItems;
typedef std::vector < std::pair <int, int> > TPairs;

有没有办法在一步中将对中的所有第一项转换为另一个向量

int main ()
{
TItems items;
TPairs pairs;

pairs.push_back (std::make_pair(1,3));
pairs.push_back (std::make_pair(5,7));

std::transform( items.begin(), items.end(), items.begin(), comp ( &pairs ) );

return 0;
}

如何设计仿函数?

class comp
{
private:
     TPairs *pairs;

public:
    comp ( TPairs  *pairs_ ) : pairs ( pairs_) { }

    unsigned int operator () ( const unsigned int index ) const
    {
        return  (*pairs)[index].second != pairs->end();  //Bad idea
    }
};

也许有一些没有lambda表达式和循环的用户友好方法。谢谢你的帮助。

6 个答案:

答案 0 :(得分:18)

首先,您应该使用back_inserter作为transform的第三个参数,以便将转换后的值推送到向量的后面。

其次,你需要某种类型的函数,它接受一对int并返回第一个。这应该做:

int firstElement( const std::pair<int, int> &p ) {
    return p.first;
}

现在,将各个部分放在一起:

TPairs pairs;
pairs.push_back( std::make_pair( 1, 3 ) );
pairs.push_back( std::make_pair( 5, 7 ) );

TItems items;
std::transform( pairs.begin(), pairs.end(), std::back_inserter( items ),
                firstElement );

在此代码之后,items包含1和5。

答案 1 :(得分:13)

参见frerich的或kotlinski对C ++ 03的回答。

使用lambda的C ++ 11解决方案:

std::transform(pairs.begin(), 
               pairs.end(), 
               std::back_inserter(items), 
               [](const std::pair<int, int>& p) { return p.first; });

答案 2 :(得分:7)

我真的希望你使用function varargout = GUI2(varargin) % GUI2 MATLAB code for GUI2.fig % GUI2, by itself, creates a new GUI2 or raises the existing % singleton*. % % H = GUI2 returns the handle to a new GUI2 or the handle to % the existing singleton*. % % GUI2('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in GUI2.M with the given input arguments. % % GUI2('Property','Value',...) creates a new GUI2 or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI2 before GUI2_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to GUI2_OpeningFcn via varargin. % % *See GUI2 Options on GUIDE Tools menu. Choose "GUI2 allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help GUI2 % Last Modified by GUIDE v2.5 14-Aug-2015 10:39:46 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @GUI2_OpeningFcn, ... 'gui_OutputFcn', @GUI2_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before GUI2 is made visible. function GUI2_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to GUI2 (see VARARGIN) % Choose default command line output for GUI2 handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes GUI2 wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = GUI2_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on button press in startAnalysis. function startAnalysis_Callback(hObject, eventdata, handles) % hObject handle to startAnalysis (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) disp(handles.ampmin) function ampmin_Callback(hObject, eventdata, handles) % hObject handle to ampmin (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ampmin as text % str2double(get(hObject,'String')) returns contents of ampmin as a double handles.ampmin = str2double(get(hObject,'String')); % Update handles structure guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function ampmin_CreateFcn(hObject, eventdata, handles) % hObject handle to ampmin (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end handles.ampmin = 1.0; disp(handles.ampmin) set(hObject, 'String', num2str(handles.ampmin)) % Update handles structure guidata(hObject, handles); 作为函子,因为它已经作为库函数提供了!!

如果我们能写出这一行,那会不会很棒!?

std::get

......但它比那更可怕。您需要消除歧义使用哪个std::transform(pairs.begin(), pairs.end(), std::back_inserter(items), std::get<0>);

get

问题是,int main() { std::vector<int> items; std::vector<std::pair<int, int>> pairs; pairs.push_back(std::make_pair(1, 3)); pairs.push_back(std::make_pair(5, 7)); std::transform(pairs.begin(), pairs.end(), std::back_inserter(items), (const int& (*)(const std::pair<int, int>&))std::get<0>); return 0; } is overloaded将1. std::get,2。pair&和3. const pair&作为参数,以便它将适用于任何类型的对作为输入。不幸的是,重载会妨碍pair&&的模板类型推导,所以我们的原始行

std::transform

产量

std::transform(pairs.begin(), pairs.end(), std::back_inserter(items), std::get<0>);

在推断 error: no matching function for call to ‘transform(std::vector<std::pair<int, int> >::iterator, std::vector<std::pair<int, int> >::iterator, std::back_insert_iterator<std::vector<int> >, <unresolved overloaded function type>)’ std::transform(pairs.begin(), pairs.end(), std::back_inserter(items), std::get<0>); ^ ... /usr/include/c++/4.8/bits/stl_algo.h:4915:5: note: template argument deduction/substitution failed: note: couldn't deduce template parameter ‘_UnaryOperation’ std::transform(pairs.begin(), pairs.end(), std::back_inserter(items), std::get<0>); 的模板时,它不知道您要求的std::get超载,因此您必须手动指定它。将函数指针强制转换为正确的类型告诉编译器,“嘿,请使用std::transform获取get的重载并返回const&!”

但至少我们正在使用标准库组件(yay)?

就行数而言,它并不比其他选项更糟糕: http://ideone.com/6dfzxz

答案 3 :(得分:3)

这个怎么样?

items.reserve(pairs.size());
for (size_t it = 0; it < pairs.size(); ++it) {
    items.push_back(pairs[it].first);
}

易于理解和调试。

答案 4 :(得分:2)

如何使用std::bind

std::transform(pairs.begin(), 
               pairs.end(), 
               std::back_inserter(items), 
               std::bind(&TPairs::value_type::first, std::placeholders::_1));

(对于非C ++ 11代码,将std::bind替换为boost::bind

答案 5 :(得分:1)

C ++ 11中的另一种可能性是std::mem_fn,类似于使用std::bind的解决方案:

std::transform(pairs.begin(), 
               pairs.end(), 
               std::back_inserter(items), 
               std::mem_fn(&std::pair<int,int>::first)               
);