2017-02-16 88 views
0

我正在实现一个MPI代码,并且我正在使用MPI_Bcast函数。其中一个函数的组件是发送的数据的数量,这里的数据的大小是l_nMinplacesPos。我想分享这个向量的大小。我试过一次sizeof l_nMinplacesPos返回32,当我用l_nMinplacesPos.size()我得到2作为矢量的大小!!!。我很困惑哪一个显示矢量的实际大小?他们之间有什么区别?sizeof和.size()之间的区别为一个向量C++

void ParaStochSimulator::broad_casting(long j){ 
std::cout << "i'm broad_casting" << std::endl; 
l_nMinplacesPos = (*m_pcTransitionsInfo)[j]->GetManipulatedPlaces(); 
double val; 
l_anMarking.reserve(l_nMinplacesPos.size()); 
for (auto lnpos : l_nMinplacesPos) 
{ 
    val = m_anCurrentMarking[lnpos]; 
    l_anMarking.push_back(val); 
} 
for (auto marking : l_anMarking) 
{ 
    std::cout << marking << std::endl; 
} 
MPI_Bcast(&l_anMarking, sizeof l_nMinplacesPos, MPI_DOUBLE, 0, MPI_COMM_WORLD); //->here i used l_nMinplacesPos.size() instead. 

}

void ParaStochSimulator::SimulateSingleRun() 
{ 
//prepare a run 
PrepareRun(); 
while ((m_nCurrentTime < m_nOutputEndPoint) && IsSimulationRunning()) 
    { 
    deterMinTau(); 
    if (mnprocess_id == 0) 
    { 
     SimulateSingleStep1(); 
     std::cout << "current time:*****" << m_nCurrentTime << std::endl; 
     broad_casting(m_nMinTransPos); 
     std::cout << "size of mani place :" << sizeof l_nMinplacesPos << std::endl; 

    } 
} 
PostProcessRun(); 
MPI_Bcast(&l_anMarking, sizeof l_nMinplacesPos, MPI_DOUBLE, 0, MPI_COMM_WORLD); //->here i used l_nMinplacesPos.size() instead. 
std::cout << "size of mani place :" << sizeof l_nMinplacesPos << std::endl; 


} 
+1

你想知道向量中有多少条目?然后你使用'vector :: size()'。 sizeof()'没有办法可以帮助你,因为它是一个*编译时*常量。它不知道你在运行时将多少个项目放入向量中。 – PaulMcKenzie

+1

也'sizeof'返回一个类型'T'占用的字节数。这就是为什么它只知道编译时信息。你可以做一个小测试,发现'sizeof(your_vector)'不管你有没有物品,或者你的矢量中有10,000个物品,sizeof(your_vector)都是一样的。 – PaulMcKenzie

+1

MPI只是像memcpy一样复制内存。由于vector不是一成不变的,所以无论大小如何,这都是未定义的行为。 – Dani

回答

4

.size()返回在矢量元素的数量。这就是你应该使用的。

sizeof给出了对象定义使用的字节的数,不包括通过使用指针分配的任何附加存储。它是编译器在编译时根据vector类的声明生成的静态常量。

0

值得一提的sizeof()也是这样的一个事实,即当您直接处理数组的单元格内容(特别是字符串)时,它可能会将该特定单元格的长度限制为8个字节。在我的实践考试中,我有一项任务是创建一个C/C++程序,它定位插入到数组中的每个单词的第一个字母。在使用sizeof()后,它只返回该数组的前8个字符,其余部分已经被丢失,所以要小心。

+0

谢谢大家现在我明白了 –

+0

不客气。 – TheInvisibleMan

相关问题