在声明字符串集时,我有几个单词需要初始化。
...
using namespace std;
set<string> str;
/*str has to contain some names like "John", "Kelly", "Amanda", "Kim".*/
我不想每次都使用
str.insert("Name");
。
如有任何帮助,我们将不胜感激。
使用C++11:
std::set<std::string> str = {"John", "Kelly", "Amanda", "Kim"};
否则:
std::string tmp[] = {"John", "Kelly", "Amanda", "Kim"};
std::set<std::string> str(tmp, tmp + sizeof(tmp) / sizeof(tmp[0]));
在 C++11 中
使用初始化列表。
std::set<std::string> str { "John", "Kelly", "Amanda", "Kim" };
在C++03中(我投票支持@john的答案。这非常接近我给出的答案。)
使用
std::set( InputIterator first, InputIterator last, ...)
构造函数。
std::string init[] = { "John", "Kelly", "Amanda", "Kim" };
std::set<std::string> str(init, init + sizeof(init)/sizeof(init[0]) );
有很多方法可以做到这一点,这里是一个
string init[] = { "John", "Kelly", "Amanda", "Kim" };
set<string> str(init, init + 4);
如果你不是 c++0x:
你应该看看 boost::assign
http://www.boost.org/doc/libs/1_39_0/libs/assign/doc/index.html#list_of
另请看:
#include <boost/assign/list_of.hpp>
#include <vector>
#include <set>
using namespace std;
using namespace boost::assign;
int main()
{
set<int> A = list_of(1)(2)(3)(4);
return 0; // not checked if compile
}
有多种方法可以做到这一点。使用 C++11,您可以尝试...
std::set<std::string> set {
"John", "Kelly", "Amanda", "Kim"
};
std::begin
和 std::end
...
std::string vals[] = { "John", "Kelly", "Amanda", "Kim" };
std::set<std::string> set(std::begin(vals), std::end(vals));
创建一个字符串数组(C 数组)并用它的值初始化该集合(数组指针作为迭代器):
std::string values[] = { "John", "Kelly", "Amanda", "Kim" };
std::set s(values,values + sizeof(values)/sizeof(std::string));