C++ 中的列表<字符串>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14417513/
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
List<string> in C++
提问by Mahdi Tahsildari
I'm cool with C# but am new to C++. I searched but found lots of different solutions which mostly do not work maybe because there are different versions of C++.
我对 C# 很酷,但对 C++ 不熟悉。我搜索但发现了许多不同的解决方案,这些解决方案大多不起作用,可能是因为 C++ 的版本不同。
I'm using turbo C++ 4.5, I want something like C#'s List of strings
我正在使用 turbo C++ 4.5,我想要类似 C# 的字符串列表
List<string> s = new List<string>();
s.Add("1");
I know a bit about C++ arrays, but I do not know the count of items at declaration time and that's why I want List-like solution so that I can declare once and add items later.
我对 C++ 数组有所了解,但我不知道声明时的项目数,这就是为什么我想要类似 List 的解决方案,以便我可以声明一次并在以后添加项目。
someone told me I should do it using pointers but I don't know how. Is it possible? or there any ways?
有人告诉我我应该用指针来做,但我不知道怎么做。是否可以?或者有什么办法?
Please if you have an answer explain it cause I really like to learn, thanks.
如果您有答案,请解释一下,因为我真的很喜欢学习,谢谢。
回答by David Heffernan
The equivalent to C# List<T>
is std::vector<T>
. The C++ code that corresponds to your C# code is this:
相当于 C# 的List<T>
是std::vector<T>
. 与您的 C# 代码对应的 C++ 代码是这样的:
using namespace std;
....
vector<string> s;
s.push_back("1");
You should not take the advice to write such a class for yourself. Where they are appropriate, always use the standard containers.
您不应该接受建议为自己编写这样的类。在合适的地方,始终使用标准容器。