[英]Element-wise “OR” operation on vectors in C++
我试图在C ++中的向量上使用or(|)运算符。 经过数小时的研究,我找不到直接在矢量上运行的任何函数,因此,我目前正在编写如下内容:
int len = 10;
std::vector<bool> v1(len);
std::vector<bool> v2(len);
std::vector<bool> vout(len);
//Some code to determine the content of v1 and v2
for(int i = 0; i < len ; i++)
{
vout[i] = v1[i] | v2[i];
}
但是,我认为这会使我的代码变慢,因此我想知道是否有任何方法可以对两个向量使用or运算符?
尝试使用std::transform
: http : //www.cplusplus.com/reference/algorithm/transform/
// transform algorithm example
#include <iostream> // std::cout
#include <algorithm> // std::transform
#include <vector> // std::vector
#include <functional> // std::plus
int op_increase (int i) { return ++i; }
int main () {
std::vector<int> foo;
std::vector<int> bar;
// set some values:
for (int i=1; i<6; i++)
foo.push_back (i*10); // foo: 10 20 30 40 50
bar.resize(foo.size()); // allocate space
std::transform (foo.begin(), foo.end(), bar.begin(), op_increase);
// bar: 11 21 31 41 51
// std::plus adds together its two arguments:
std::transform (foo.begin(), foo.end(), bar.begin(), foo.begin(), std::plus<int>());
// foo: 21 41 61 81 101
std::cout << "foo contains:";
for (std::vector<int>::iterator it=foo.begin(); it!=foo.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
看来您的意思如下
#include <iostream>
#include <iomanip>
#include <vector>
#include <functional>
#include <algorithm>
#include <iterator>
int main()
{
std::vector<bool> v1 = { 1, 0, 1, 1, 0, 0 };
std::vector<bool> v2 = { 0, 0, 0, 0, 0, 1 };
std::vector<bool> v3;
v3.reserve( v1.size() );
std::transform( v1.begin(), v1.end(), v2.begin(),
std::back_inserter( v3 ), std::logical_or<>() );
for ( auto item : v1 ) std::cout << std::boolalpha<< item << ' ';
std::cout << std::endl;
std::cout << "OR\n";
for ( auto item : v1 ) std::cout << std::boolalpha<< item << ' ';
std::cout << std::endl;
std::cout << "=\n";
for ( auto item : v3 ) std::cout << std::boolalpha<< item << ' ';
std::cout << std::endl;
return 0;
}
程序输出为
true false true true false false
OR
true false true true false false
=
true false true true false true
也就是说,您可以使用标准算法std::transform
和功能对象std::logical_or
。
您可以覆盖| 像这样的运算符:
std::vector<bool> operator |(std::vector<bool> v1,std::vector<bool> v2)
{
std::vector<bool> result(len);
for(int i = 0; i < len ; i++)
result[i] = v1[i] | v2[i];
return result;
}
主要是你打电话
std::vctor<bool> result(len) = v1 | v2;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.