[英]The difference between sizeof and .size() for a vector c++
我正在實現MPI代碼,並且正在使用MPI_Bcast
函數。 函數的組成部分之一是發送的數據數量,在此是稱為l_nMinplacesPos
的向量的大小。 我想分享這個向量的大小。 我曾經嘗試過一次sizeof l_nMinplacesPos
返回32,當我使用l_nMinplacesPos.size()
我得到2作為向量的大小! 我很困惑其中哪一個顯示矢量的實際大小? 兩者之間有什么區別?
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;
}
.size()
返回向量中元素的數量。 那就是你應該使用的。
sizeof
提供了對象定義使用的字節數,不包括它通過使用指針分配的任何其他存儲。 它是編譯器在編譯時根據vector
類的聲明生成的靜態常量。
值得一提的是sizeof()
,當您直接處理數組單元格的內容(尤其是字符串)時,它可能會將特定單元格的長度縮短為8個字節。 在我的實踐考試中,我有一個創建C / C ++程序的任務,該程序將找到插入到數組中的每個單詞的第一個字母。 使用sizeof()
它僅返回該數組的前8個字符,其余的已被拋出內存,因此請當心。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.