C++, Sort One Vector Based On Another One

The best example I've got is that I want to sort Names based on their Score.

vector <string> Names {"Karl", "Martin", "Paul", "Jennie"};
vector <int> Score{45, 5, 14, 24};

So if I sort the score to {5, 14, 24, 45}, the names should also be sorted based on their score.

As already suggested in other answers: Combining the name and the score of each individual is likely the simplest solution.

Generically, this can be achieved with what is sometimes referred to as a "zip" operation: Combining two vectors into a vector of pairs - along with a corresponding "unzip".

Implemented generically, this may look as follows:

#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
#include <iterator>

// Fill the zipped vector with pairs consisting of the
// corresponding elements of a and b. (This assumes 
// that the vectors have equal length)
template <typename A, typename B>
void zip(
    const std::vector<A> &a, 
    const std::vector<B> &b, 
    std::vector<std::pair<A,B>> &zipped)
{
    for(size_t i=0; i<a.size(); ++i)
    {
        zipped.push_back(std::make_pair(a[i], b[i]));
    }
}

// Write the first and second element of the pairs in 
// the given zipped vector into a and b. (This assumes 
// that the vectors have equal length)
template <typename A, typename B>
void unzip(
    const std::vector<std::pair<A, B>> &zipped, 
    std::vector<A> &a, 
    std::vector<B> &b)
{
    for(size_t i=0; i<a.size(); i++)
    {
        a[i] = zipped[i].first;
        b[i] = zipped[i].second;
    }
}


int main(int argc, char* argv[])
{
    std::vector<std::string> names {"Karl", "Martin", "Paul", "Jennie"};
    std::vector<int> score {45, 5, 14, 24};

    // Zip the vectors together
    std::vector<std::pair<std::string,int>> zipped;
    zip(names, score, zipped);

    // Sort the vector of pairs
    std::sort(std::begin(zipped), std::end(zipped), 
        [&](const auto& a, const auto& b)
        {
            return a.second > b.second;
        });

    // Write the sorted pairs back to the original vectors
    unzip(zipped, names, score);

    for(size_t i=0; i<names.size(); i++)
    {
        std::cout << names[i] << " : " << score[i] << std::endl;
    }
    return 0;
}

C Programming Tutorial for Beginners, Learn C the Hard Way: Practical Exercises on the Computational Subjects You Keep Avoiding (Like C) Stock analysis for Citigroup Inc (C:New York) including stock price, stock chart, company news, key statistics, fundamentals and company profile.

Best way to do this would be to have a struct which combines the names with their scores and have one vector.

struct Person
{
    std::string Name;
    int Score;
};

Then you can declare your vector:

std::vector<Person> people{ { "Karl", 45 }, { "Martin", 5 }, { "Paul", 14 } };

And sorting it is easy with std::sort from <algorithm>:

std::sort(people.begin(), people.end(), 
               [](const auto& i, const auto& j) { return i.Score < j.Score; } );

Or you can change the lambda if you want to sort in descending order:

std::sort(people.begin(), people.end(), 
               [](const auto& i, const auto& j) { return i.Score > j.Score; } );

"C" Programming Language: Brian Kernighan, This course will give you a full introduction into all of the core concepts in the C programming Duration: 3:46:13 Posted: Aug 15, 2018 Discover historical prices for C stock on Yahoo Finance. View daily, weekly or monthly format back to when Citigroup, Inc. stock was issued.

If you cannot merge the data into a vector of pairs or struct with both, you could create a vector of iterators, or the indexes from 0 to size-1. Then sort this using a custom comparator. Finally, create a new vector, populating it using the iterators or indexes.

template<class T1, class A1, class T2, class A2>
std::vector<T1, A1> sort_by(
  std::vector<T1,A1> const& vin, std::vector<T2,A2> const& keys
){
  std::vector<std::size_t> is;
  is.reserve(vin.size());
  for (auto&& unused:keys)
    is.push_back(is.size());
  std::sort(begin(is),end(is),[&](std::size_t l, std::size_t r){
    return keys[l]<keys[r];
  });
  std::vector<T1, A1> r;
  r.reserve(vin.size());
  for(std::size_t i:is)
    r.push_back(vin[i]);
  return r;
}

Learn C, "C" is one of the most widely used programming languages of all time. Prof Brian Kernighan Duration: 8:26 Posted: Aug 18, 2015 C programming is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to develop the UNIX operating system. C is the most widely used computer language. It keeps fluctuating at number one scale of popularity

An alternative to consolidating the names and scores into a single structure is to create an index list and sort that:

 std::vector<int> indices(Names.size());
 std::iota(indices.begin(), indices.end(), 0);
 std::sort(indices.begin(), indices.end(),
           [&](int A, int B) -> bool {
                return Score[A] < Score[B];
            });

Now indices can be used to index Names and Scores in the desired sorted order.

Learn C Programming, learn-c.org is a free interactive C tutorial for people who want to learn C, fast. Programming Languages Development - C++ has been used extensively in developing new programming languages like C#, Java, JavaScript, Perl, UNIX’s C Shell, PHP and Python, and Verilog etc. Computation Programming - C++ is the best friends of scientists because of fast speed and computational efficiencies.

One way you could do this would be to store the Names and Scores in a single data structure such as a std::vector<std::pair<std::string,int>> and then sorting can be done as follows:

#include <algorithm>
#include <vector>
#include <string>
#include <utility>
//...
std::vector<std::pair<std::string, int>> names_scores_vec;
// ... populate names_scores_vec...
// lambda for sorting, change to > for descending order
auto sort_by_scores = [](const std::pair<string,int>& _lhs, 
    const std::pair<string,int>& _rhs) { return _lhs.second < _rhs.second; };
std::sort(names_scores_vec.begin(), names_scores_vec.end(), sort_by_scores);

Alternatively, use storage such as a std::map or std::multimap if you want repeated keys (i.e. repeated names allowed).

C Tutorial, Tutorials Examples References Compiler. C is a powerful general-purpose programming language. It can be used to develop software like operating systems, databases, compilers, and so on. Learn about C with our data and independent analysis including price, star rating, valuation, dividends, and financials. Start a 14-day free trial to Morningstar Premium to unlock our take on C.

C Language - Overview, C programming is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis M. Ritchie at the Bell Telephone� C - switch statement - A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is chec

Cprogramming.com: Learn C and C++ Programming, C Language - Overview - C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system � Microsoft C++, C, and Assembler documentation. Learn how to use C++, C, and assembly language to develop applications, services, and tools for your platforms and devices.

What is C?, The best site for C and C++ programming. Popular, beginner-friendly C and C++ tutorials to help you become an expert! C-SPAN.org gives you access to C-SPAN's daily coverage of Washington and more than 200,000 hours of extensively indexed and archived C-SPAN video.

Comments
  • Why not having a std::vector<std::pair<int,std::string>> instead?
  • Or at least make a struct with an int and a string and have a vector of that.
  • Or sort a vector of indices std::vector<size_t> providing a custom comparator comp(i, j) := Score[i] < Score[j].
  • Why is the struct name plural? It should be Person with the vector named people.
  • Because it's too late for me to think straight. Fixed and all.
  • If you could show an example of this I would be very grateful.
  • No love for std::iota?
  • Unfortunately it doesn't seem to work under GCC even after I fixed the typedef usage in value_iterator_t . Also, you shouldn't use names starting with _[A-Z] not put stuff into namespace std. Both make the behaviour of your code undefined.
  • Thx for the find, I fixed it now and works on GCC as well.