【问题标题】:Insert value into vector in a list将值插入到列表中的向量中
【发布时间】:2015-07-09 07:58:21
【问题描述】:

我有一个带有向量的特定列表。我想为向量添加一个值。我该怎么做?

这是我的代码:

//creating the list with vectors
std::list< vector<string> > adjacencylist;
//adding some vectors to the list...
adjacencylist.push_back(std::vector<std::string>(1, "String"));
adjacencylist.push_back(std::vector<std::string>(1, "String"));
adjacencylist.push_back(std::vector<std::string>(1, "String"));

现在我想向列表中的向量添加值... 我为此尝试过:

std::list< vector<string> >::const_iterator it = adjacencylist.begin();
(*it).push_back("Some more String");

我认为这会奏效。所以我可以遍历所有向量并插入我想要的值。但它不起作用。这里是编译器的输出:

example.cpp: In function ‘int main(int, char**)’:
example.cpp:148:31: error: passing ‘const std::vector<std::basic_string<char> >’ as ‘this’ argument of ‘void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = std::basic_string<char>; _Alloc = std::allocator<std::basic_string<char> >; std::vector<_Tp, _Alloc>::value_type = std::basic_string<char>]’ discards qualifiers [-fpermissive]
     (*it).push_back("test");

【问题讨论】:

  • 改用push_back
  • 它被称为push_back
  • push_back 也不起作用:example.cpp:147:50: error: passing ‘const std::vector&lt;std::basic_string&lt;char&gt; &gt;’ as ‘this’ argument of ‘void std::vector&lt;_Tp, _Alloc&gt;::push_back(const value_type&amp;) [with _Tp = std::basic_string&lt;char&gt;; _Alloc = std::allocator&lt;std::basic_string&lt;char&gt; &gt;; std::vector&lt;_Tp, _Alloc&gt;::value_type = std::basic_string&lt;char&gt;]’ discards qualifiers [-fpermissive] (*it).push_back("test");
  • 使用iterator,而不是const_iterator
  • @beta 谢谢!这解决了问题

标签: c++ list vector c++98


【解决方案1】:

因为您已将it 声明为const_iterator,所以您已将it 引用的内容无法编辑。当您调用push_back 时,您正在尝试编辑it 指向的vector。您需要更换:

std::list< vector<string> >::const_iterator it = adjacencylist.begin();
(*it).push_back("Some more String"); 

std::list< vector<string> >::iterator it = adjacencylist.begin();
(*it).push_back("Some more String");

阅读一般的constnesshere,在const_iteratorhere有更具体的信息。

【讨论】:

    【解决方案2】:

    只使用一个迭代器。您也可以使用it -&gt; push_back 代替(*it).push_back

    这是一个例子:

    for (list< vector<string> > it = adjacencylist.begin(); it != adjacencylist.end(); ++it)
    {
        it -> push_back("Your std::string");
    }
    

    【讨论】:

      猜你喜欢
      • 2018-06-28
      • 1970-01-01
      • 1970-01-01
      • 2021-09-08
      • 2017-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多