[英]STL copy, pair, vector and inserter
I have an input of: 我有一个输入:
1 a
2 b
..
I would like to insert them to a vector of pairs, with copy function, like this: 我想将它们插入到具有复制功能的对矢量中,如下所示:
#include <vector>
#include <iterator>
#include <algorithm>
#include <iostream>
int main(void) {
std::vector<std::pair<int, char>> v;
std::copy(std::istream_iterator<std::pair<int, char>>(std::cin), std::istream_iterator<std::pair<int, char>>(), std::back_inserter(v));
for(auto pair: v)
std::cout << pair.first << std::endl;
return 0;
}
However, this will not compile: error: no match for 'operator>>'
, since it probably needs an operator overloading. 但是,这不会编译:
error: no match for 'operator>>'
,因为它可能需要运算符重载。
Does that mean that I will have to create my own class, which inhertis from std::vector
, and then overload the operator? 这是否意味着我将不得不创建自己的类,它来自
std::vector
,然后重载运算符?
I would like to avoid using my own class, instead of the standard vector class. 我想避免使用我自己的类,而不是标准的矢量类。
The problem is not with std::vector
, it's std::istream_iterator
. 问题不在于
std::vector
,而是std::istream_iterator
。 The reason being that std::pair
doesn't have a deserialization operator defined. 原因是
std::pair
没有定义反序列化运算符。
You can still use std::vector
and std::back_insert_iterator
, but you'll need to define your own input iterator. 您仍然可以使用
std::vector
和std::back_insert_iterator
,但是您需要定义自己的输入迭代器。 One that reads pairs of values. 读取价值对的人。
Some people may suggest that you define operator>>
for your pairs, but that is an unreliable technique. 有些人可能会建议你为你的对定义
operator>>
,但这是一种不可靠的技术。 It will depend on the operator being defined before you include <algorithm>
and <iterator>
. 它将取决于在包含
<algorithm>
和<iterator>
之前定义的运算符。
You could copy it through a proxy object: 您可以通过代理对象复制它:
#include <vector>
#include <iterator>
#include <algorithm>
#include <iostream>
struct proxy
{
friend auto operator>>(std::istream& is, proxy& prox) -> std::istream&
{
is >> std::get<0>(prox.target);
is >> std::get<1>(prox.target);
return is;
}
operator std::pair<int, char>() const {
return target;
}
std::pair<int, char> target;
};
int main(void) {
std::vector<std::pair<int, char>> v;
std::copy(std::istream_iterator<proxy>(std::cin),
std::istream_iterator<proxy>(),
std::back_inserter(v));
for(auto pair: v)
std::cout << pair.first << std::endl;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.