Search code examples
c++std-pair

Index-based assignment in the loop for Pair, C++


I am new to C++. I want to assign the values to my tuple inside the loop. The following does not work.

#include<utility>

std::pair<int, int> myPair;

int main() {
    for(int i=0; i<2; i++) {
        std::get<i>(myPair) = i;
    }
}

How could I do it correctly?


Solution

  • Do you have a reason to insist on doing this in a loop? If not, you can just assign to mypair.first and mypair.second.

    #include<utility>
    
    std::pair<int, int> myPair;
    
    int main() {
        myPair.first = 1;
        myPair.second = 2;
    }
    

    A very useful website to check what's available for standard library types is cppreference.com

    Maybe you actually want a std::vector?

    #include <vector>
    
    int get_next_value(int); // Not defined in this example.
    // You get your values from somewhere...
    
    // note that global variables like this might not be the best idea.
    std::vector<int> values; 
    
    int main() {
        for (int i=0; i < 2; ++i) {
            values.push_back(get_next_value(i));
        }
    }