【问题标题】:Inserting elements of vector into set, while printing set elements gets compilation issue c++98将向量的元素插入集合,同时打印集合元素得到编译问题c ++ 98
【发布时间】:2021-08-14 15:01:23
【问题描述】:

我将向量值插入到集合中。之后,我尝试在遇到编译问题的地方打印设置值。请帮助我理解我做错了什么。

code:
#include<iostream>
#include<set>
#include<vector>

using namespace std;

int main()
{
   set<string> s1;
   vector<string> v1;
   v1.push_back("Hello");
   v1.push_back("Hello");
   v1.push_back("Hi");
   v1.push_back("Hi");
   v1.push_back("Cya");

   for(int i=0; i<v1.size(); i++)
   {
      s1.insert(v1[i]);
   }

   for(int i= 0; i<s1.size(); i++)
   {
       cout<<s1[i]<<endl;
   }

   return 0;
}
compilation error:
 error: no match for ‘operator[]’ (operand types are ‘std::set<std::basic_string<char> >’ and ‘int’)
        cout<<s1[i]<<endl;

【问题讨论】:

标签: c++ vector stl set c++98


【解决方案1】:

您使用迭代器接口:

for (std::set<std::string>::const_iterator it = s1.begin(), end = s1.end();
     it != end; ++it) {
  std::cout << *it << '\n';
}

你也可以使用std::copy:

std::copy(s1.begin(), s1.end(),
          std::ostream_iterator<std::string>(std::cout, "\n"));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    相关资源
    最近更新 更多