我试图在C ++的循环中操纵0初始化向量的值。 但是,当我打印出矢量的值时,它只显示" myFunction"中的合理值。除此之外,价值观没有改变。 这是我的例子草图:
vector<float> meanDistances(numDescriptors);
for (int i = 0; i < numDescriptors, i++)
{
myFunction(arg1, arg2,...,meanDistances[i]));
cout << "meanDistance OUTSIDE myFunction: " << meanDistances[i] << endl;
}
这就是&#34; myFunction&#34;看起来像:
void myFunction(arg1, arg2, ..., float & meanDistance)
{
meanDistance = someFloatNumber;
cout << "meanDistance INSIDE myFunction: " << meanDistance << endl;
}
如何将矢量的单个元素作为函数的引用传递?
编辑:
这里有一些代码
boost::thread_group threadGroup;
for (int i = 0; i < numDescs ; i++ )
{
int threadIdx = i % numThreads;
vecHists[i].convertTo(vecHists[i], CV_32F);
threadGroup.create_thread(boost::bind( &myFunction, vecHists[i],vecHists[i],vecDistanceMats[threadIdx], meanDistances[i]));
sleep(1);
if(threadIdx == numThreads-1 || i == numDescs-1)
{
threadGroup.join_all();
for (int j = 0; j < numThreads ; j++)
{
sumDistanceMats += vecDistanceMats[j];
}
}
}
for (int i = 0; i < numDescs ; i++ )
{
cout << "meanDistances OUTSIDE myFunction after all threads are joined again: " << meanDistances[i] << endl;
}
EDIT2:
事实证明,这个函数的问题在于boost::threadGroup
的功能。如果我通过1x1 dim opencv Mats vector<float> meanDistances
的向量交换vector<cv::Mat> meanDistances
向量,一切正常。
当然,我也相应地修改了myFunction
:
void myFunction(arg1, arg2, ..., Mat& matMeanDistance)
{
meanDistance.at<float>(0,0) = someFloatNumber;
cout << "meanDistance INSIDE myFunction: " << matMeanDistance.at<float>(0,0) << endl;
}
所以某种方式boost::threadGroup
处理float
的向量不同于cv::Mat
的向量
答案 0 :(得分:0)
下面你将找到一个例子,说明如何通过引用(使用 range-for )或通过lambda辅助的std::transform
算法修改向量中的所有元素。
#include <vector>
#include <iostream>
#include <algorithm>
// utility function to print to screen
template<typename T>
void show(const T& v) {
for(const auto & vi : v) {
std::cout << vi << " ";
}
std::cout << std::endl;
}
// function used to modify by reference
void fun(double arg, double& vi) {
vi += arg;
}
int main() {
// initialize ten elements to 0.0
std::vector<double> v(10, 0.0);
std::cout << "Initialized as: " << std::endl;
show(v);
// modification using references in a loop
for(auto & vi : v) {
fun(2.0, vi);
}
std::cout << "Modified to: " << std::endl;
show(v);
// modification using an algorithm and a lambda (this one modifies by value)
std::transform(v.begin(), v.end(), v.begin(),
[](double vi) { return vi + 3; });
std::cout << "Modified using std::transform() and lambda" << std::endl;
show(v);
}
编译并运行:
$ g++ example.cpp -std=c++14 -Wall -Wextra
$ ./a.out
Initialized as:
0 0 0 0 0 0 0 0 0 0
Modified to:
2 2 2 2 2 2 2 2 2 2
Modified using std::transform() and lambda
5 5 5 5 5 5 5 5 5 5