使用构造函数将元素插入 std::set

发布于 2024-08-24 12:41:43 字数 455 浏览 4 评论 0原文

是否可以像 std::list 一样向 std::set 插入一个新元素,例如:

//insert one element named "string" to sublist of mylist

std::list< std::list<string> > mylist;
mylist.push_back(std::list<string>(1, "string"));

现在,mylist 有一个 std::string 类型的元素它的子列表类型为 std::list。

如果 std::set 是 std::list 我的列表的子集,你怎么能做同样的事情,即

std::list<std::set <string>> mylist;

如果你不能那么为什么不呢?

is it possible to insert a new element to std::set like in case of std::list for example:

//insert one element named "string" to sublist of mylist

std::list< std::list<string> > mylist;
mylist.push_back(std::list<string>(1, "string"));

Now, mylist has one element of type std::string in its sub-list of type std::list.

How can you do the same in if std::set is the sub-set of std::list my list i.e

std::list<std::set <string>> mylist;

if you can't then why not?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

时光是把杀猪刀 2024-08-31 12:41:43

我认为这应该可以解决问题:

int main()
{
    string s = "test";
    set<string> mySet(&s, &s+1);

    cout << mySet.size() << " " << *mySet.begin();

    return 0;
}

有关将 &s 视为数组的合法性和有效性的澄清,请参阅此讨论:字符串 s; &s+1;合法的? UB?

I think this should do the trick:

int main()
{
    string s = "test";
    set<string> mySet(&s, &s+1);

    cout << mySet.size() << " " << *mySet.begin();

    return 0;
}

For clarification on the legality and validity of treating &s as an array, see this discussion: string s; &s+1; Legal? UB?

用心笑 2024-08-31 12:41:43

std::set 没有需要插入元素的构造函数。您能做的最好的事情就是使用范围构造函数:

int a[] = {1,2,3,4,5};
std::set<int> foo(a, a+5);  // insert the values 1 through 5 into foo

此版本采用 beginend 迭代器来描述要插入到集合中的范围。您也可以选择提供排序标准。这不完全是你想要的,但也很接近了。因此,如果您将元素存储在容器 v 中,您可以将一个新集合插入到您的列表中,如下所示:

list<set<string> > myList;
myList.push_back(set<string>(v.begin(), v.end()));

std::set doesn't have a constructor that takes an element to be inserted. The best you can do is use the range constructor:

int a[] = {1,2,3,4,5};
std::set<int> foo(a, a+5);  // insert the values 1 through 5 into foo

This version takes a begin and end iterator describing the range to be inserted into the set. You can optionally supply a sorting criterion as well. It's not quite what you wanted, but it's close. So if you had your elements stored in a container v, you can insert a new set to your list like this:

list<set<string> > myList;
myList.push_back(set<string>(v.begin(), v.end()));
心房的律动 2024-08-31 12:41:43

或者,在 C++0x 中:

    std::list<std::set<int>> foo;
    foo.push_back({1,2,3});

Or, in C++0x:

    std::list<std::set<int>> foo;
    foo.push_back({1,2,3});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文