繁体   English   中英

在 C++11 中初始化字符串列表

[英]Initializing list of strings in c++11

我试图使用以下代码在 c++11 中初始化字符串列表,但由于各种原因而失败。 错误说我需要使用构造函数来初始化列表,我应该使用list<string> s = new list<string> [size]吗? 我在这里缺少什么?

#include<string>
#include<list>
#include<iostream>
using namespace std;

int main() {
      string s = "Mark";
      list<string> l  {"name of the guy"," is Mark"};
      cout<<s<<endl;
      int size = sizeof(l)/sizeof(l[0]);
      for (int i=0;i<size;i++) {
             cout<<l[i]<<endl;
      }
      return 0;
 }

输入/输出是

 strtest.cpp:8:47: error: in C++98 ‘l’ must be initialized by constructor, not 
 by ‘{...}’
 list<string> l  {"name of the guy"," is Mark"};

您使用的是 c++98 而不是 c++11 的编译器。如果您使用的是 gcc,则使用它

g++ -std=c++11 -o strtest strtest.cpp

你可以用gnu++11替换c ++11

列表初始值设定项仅在 C++11 中可用。 要使用 C++11,您可能必须将标志传递给编译器。 对于GCC和 Clang,这是-std=c++11

此外, std::list不提供下标运算符。 您可以像在另一个答案中一样使用std::vector ,也可以使用基于范围的 for 循环来遍历列表。

还有一些提示:

#include <string>
#include <list>
#include <iostream>

int main() {
  std::string s = "Mark";
  std::list<std::string> l {"name of the guy"," is Mark"};

  for (auto const& n : l)
    std::cout << n << '\n';
}

这里最大的问题是您正在使用列表。 在 C++ 中,列表是双向链表,因此 [] 没有任何意义。 您应该改用向量。

我会尝试:

#include<string>
#include<vector>
#include<iostream>
using namespace std;

int main() {
      string s = "Mark";
      vector<string> l = {"name of the guy"," is Mark"};
      cout<<s<<endl;
      for (int i=0;i<l.size();i++) {
             cout<<l[i]<<endl;
      }
      return 0;
 }

相反

编辑:正如其他人指出的那样,请确保您使用的是 c++ 11 而不是 c++ 98

那么这个问题的答案就是简单地将一个列表的内容复制到另一个列表中希望它有帮助:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM