C++ 列表,获取列表中的元素数量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5725693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ list, get number of elements in a list?
提问by Testing
Quick question.
I've got a list and I simply added just one element to the list
.
But when I print out myList.size()
, it returns 18
? Even though there is one element?
快速提问。我有一个列表,我只是在list
. 但是当我打印出来时myList.size()
,它返回18
?即使只有一个元素?
To add my element I use: myList.push_back(element)
;
要添加我的元素我使用:myList.push_back(element)
;
回答by Lindydancer
§23.3.6 says:
§23.3.6 说:
The member function
size()
returns the number of elements in the container.
成员函数
size()
返回容器中元素的数量。
This means that
这意味着
1) you have a broken C++ environment, or
2) you have, somehow, added more elements to your list.
1) 您的 C++ 环境已损坏,或
2) 不知何故,您在列表中添加了更多元素。
Unfortunately, it's hard to tell which is the case, as you haven't posted enough information. What would be nice is a small, complete, examples that demonstrates what you are trying to do, a description of what happens and what you expected to happen.
不幸的是,由于您没有发布足够的信息,因此很难判断是哪种情况。最好是一个小而完整的示例,它展示了您正在尝试做什么,对发生的事情以及您期望发生的事情的描述。
回答by mukeshkumar
Another possibility that i can think of is that the list has been created with a finite size using the following constructor :
我能想到的另一种可能性是使用以下构造函数创建了具有有限大小的列表:
explicit list ( size_type n, const T& value= T(), const Allocator& = Allocator() );
回答by kunal
At the start do MyList.clear()
then push the elements and finally check the size.
在开始做MyList.clear()
然后推动元素,最后检查大小。
回答by Ali Ahmed
If I am not wrong you want to do something like this...I performed a quick search and found the following..
如果我没有错,你想做这样的事情......我进行了快速搜索并找到了以下内容......
int main ()
{
list<int> myints;
cout << "0. size: " << (int) myints.size() << endl;
for (int i=0; i<10; i++) myints.push_back(i);
cout << "1. size: " << (int) myints.size() << endl;
myints.insert (myints.begin(),10,100);
cout << "2. size: " << (int) myints.size() << endl;
myints.pop_back();
cout << "3. size: " << (int) myints.size() << endl;
return 0;
}