如何通过使用set <pair <int,int>> :: iterator来迭代set <pair <int,int>> st中的值?

时间:2019-09-09 06:33:59

标签: c++ stl iteration

我正在使用set中的对,并希望打印值,并且我的编译器始终在“代码1”中显示错误,但在“代码2”中成功运行。

我知道,这两个过程在没有配对的情况下访问一个集合是相同的,但是我在使用配对到集合中时遇到了问题。

我正在使用Windows 10 + Intel和“代码块” IDE。

代码1:

import java.sql.Connection;
import java.sql.DriverManager;

public class databaseConnection {

public static void main(String[] args) throws Exception {
    getConnection();
}

public static Connection getConnection() throws Exception {
    try {
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/dbase";
        String username = "root";
        String password = "root";
        Class.forName(driver);

        Connection conn = DriverManager.getConnection(url, 
 username, password);
        System.out.println("Connected.");
        return conn;
    } catch (Exception e) {

        System.out.println(e);
    }

    return null;

}
}

代码2:

set < pair< int,int> >::iterator it;
for(it=st.begin();it!=st.end();it++){
    cout << *(it.first) << " " << *(it.second) << endl ;//error shows here
}

在“代码2”中,我的程序成功运行,但在“代码1”中,它显示了指向注释行的错误。

1 个答案:

答案 0 :(得分:3)

it是引用一对的迭代器,要访问该对,您需要先取消引用该迭代器。

cout << (*it).first << " " << (*it).second << endl ;

或更佳

cout << it->first << " " << it->second << endl ;

编辑:如果您有c++17支持。

for(auto [first, second] : st)
     std::cout<<first<<" "<<second;
相关问题